Issues with simple client server program - java

I have written two-way client-server communication in which client first sends the message and then server sends the reply. However, client is blocked while reading the reply sent by server( i.e Nothing is printed at client side however, server has sent the reply correctly). Below is the code :-
Server code:-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
// Socket for accepting connections.
private static Socket socket;
public static void main( String[] args )
{
try
{
int port = 2550;
// Creating server socket on specified port.
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started listening on port "+port);
while(true)
{
// Accept the connection and read the message.
socket = serverSocket.accept();
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String message = br.readLine();
System.out.println("Message recieved from client is :- " + message);
// Prepare and send the response back to client.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String reply = "Thanks.Your reply has been recieved";
bw.write(reply);
bw.flush();
}
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch( Exception e )
{
}
}
}
}
Client code :-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
private static Socket socket;
public static void main( String[] args )
{
try
{
String host = "localhost";
int port = 2550;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
// Send the message to the server.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String message = "This is the message from Client.\n";
bw.write(message);
bw.flush();
System.out.println("Message sent to the server :- " + message);
// Get the reply from the server.
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String reply = br.readLine();
System.out.println("Message recieved from the server :- " + reply);
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
// Closing the socket.
try
{
socket.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
}
D:\Java_P>java Server
Server started listening on port 2550
Message recieved from client is :- This is the message from Client.
D:\Java_P>java Client
Message sent to the server :- This is the message from Client.
I

This is happening because your server sends "Thanks. Your reply has been recieved" which does not contain any newline character. Reason is because in the client, buffered reader readline method blocks till it finds a newline character.
Make following changes:
String reply = "Thanks.Your reply has been recieved\nDummy line 1";
Now you can see the lines in your client logs.

Related

how to connect Restful API and socket server in java

I created restful API(with maven) which connect to MySQL. I want to connect with the Java socket server I created earlier. But I couldn't figure out how to do this. I tried to connect with HttpURLConnection over Server.java but it didn't connect yet. Is it a good way to connect? Or should i try different way for this? And also I created new maven project and putted Server.Java and Client.Java in it. But it is a just attempt. I am not sure is it necessary or not.
Server.JAVA
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Server {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
// System.out.println("Client accepted");
// HttpURLConnection attempt
URL url = new URL("http://localhost:8080/update/3");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setRequestProperty("Content-Type", "application/json");
http.setDoOutput(true);
OutputStream stream = http.getOutputStream();
String data = "{\n \"firstName\":\"Can\",\n \"lastName\":\"Doe\",\n \"occupation\":\"xxx\"\n}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
stream.write(out);
System.out.println(http.getResponseCode() + http.getResponseMessage());
http.disconnect();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Stop" is sent
while (!line.equals("Stop"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server( 5000);
}
}

Java: Simple Client Server message exchange not working

I am new to Java just started yesterday. I wrote a very simple client server java code. Client sends a message to server. The Server should display that message. And the Server should send a message to client after receiving the message. The client should display the message sent by server.
Server Code,
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class CustomServer{
public static void main(String[] args){
final int SERVER_PORT_NUMBER = 8081;
try{
ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER);
Socket clientSocketObj = serverObj.accept();
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()));
if(clientSocketObj != null){
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
// Close Streams
clientOutputStream.close();
clientInputStream.close();
}
serverObj.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Client,
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class CustomClient{
public static void main(String[] args){
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try{
Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER);
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Connecting....");
if(clientSocket != null){
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
// Close Streams
clientInputStream.close();
clientOutputStream.close();
}
clientSocket.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Neither the Server or Client receive the message. Stuck in some loop. Anyone know why?
Start by having a read of the BufferedReader's JavaDocs, which state
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed
BufferedWriter#write is not sending this, so the reader is still waiting.
A simply solution might be to use BufferedWriter#newLine after the write
And don't forget to flush the buffer when you're finished writing to it!
You may also want to take a look at try-with-resources which will provide a better resource management solution
CustomClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class CustomClient {
public static void main(String[] args) {
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try (Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER)) {
try (BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
System.out.println("Connecting....");
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
clientOutputStream.newLine();
clientOutputStream.flush();
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
CustomServer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class CustomServer {
public static void main(String[] args) {
final int SERVER_PORT_NUMBER = 8081;
try (ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER)) {
try (Socket clientSocketObj = serverObj.accept()) {
try (BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()))) {
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
clientOutputStream.newLine();
clientOutputStream.flush();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

BufferedReader Pending for Request/Response Socket Connection

I am trying to build a simple request/response server.
Client send a message to Server. Then, the server response a message to client.
Server-side Code
package com.techoffice.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
public class TcpServerAppl {
static int port = 1010;
static ServerSocket serverSocket;
static {
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.println("Server is running on " + port);
while(true){
Socket socket = null;
try{
socket = serverSocket.accept();
System.out.println("Someone is connecting to the server");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(os);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
// read message from client
String line = bufferedReader.readLine();
while(line != null && line.length() > 0){
System.out.println(line);
line = bufferedReader.readLine();
}
// reader.close();
// send message to client
System.out.println("Server starts sending message to client");
printWriter.println("This is a message sent from server");
printWriter.flush();
// printWriter.close();
} catch(Exception e){
System.err.println(e.getMessage());
} finally {
if (socket != null){
try {
socket.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
}
}
}
Client-side code
package com.techoffice.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.SocketFactory;
public class TcpClientAppl {
public static void main(String[] args) throws UnknownHostException, IOException{
// start socket connection
Socket socket = SocketFactory.getDefault().createSocket("localhost", 1010);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send message to server
printWriter.println("Send Message From Client" );
printWriter.flush();
// printWriter.close();
// read message from server
System.out.println("Client starts reading from Server");
String line = bufferedReader.readLine();
while(line != null && line.length() > 0){
System.out.println(line);
line = bufferedReader.readLine();
}
// bufferedReader.close();
// close scoket connection
socket.close();
}
}
The Server is blocked at the Buffered Reader. However, if I tried to close the Buffered Reader by closing in Print Writer in Client, the Client throw an exception of "Connection Closed".
It is known that closing in PrintWriter or BufferedReader would close the socket connection.
Update
Specifying a End of Request/Message would be one of solution. But in this case, I would not want to have an End of Request. I just want to have response for a request no matter no many line is in the request.
The client throw an exception of 'connection closed'
No it doesn't. If you uncomment the printWriter.close() line it will throw an exception 'socket closed'.
But to your real problem. The server reads lines until end of stream before it sends anything: end of stream will never occur until the peer closes the connection; and the peer isn't closing the connection, except as above; so it will never send anything and just stay blocked in readLine(); so the client will block forever in readLine() too.
As this is evidently an echo server, it should echo every line as it is received.
Question is missing exception thrown by client side. Maybe try to close everything (reader,writer) on server-side after your communication is done. BTW. you don't need to call flush before calling close. Also you can use try-catch-withResources with socket on server side

Java – Server Only Responds when the Client has Stopped

I recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.
This is the client code:
import java.io.*;
import java.net.*;
class ServerTest{
public static void main(String args[]) throws Exception{
Socket clientSocket = new Socket(myIpAdress, 8001);
//Send the message to the server
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sendMessage = "randSubstring:StackOverflowIsAwsome";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent: "+sendMessage);
String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
System.out.println("Message received from the server : " +message);
clientSocket.close();
}
}
My server code consists of two classes. This one is the listener:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket socket = new ServerSocket(8001);
while(true) {
Socket connectionSocket = socket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = input.readLine();
if(clientSentence.startsWith("randSubstring:")){
Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
connection.start();
}
Thread.sleep(300);
}
}
}
This is the thread that will not start until the client is stopped:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
public class ServerConnection implements Runnable{
private Socket serverConnection;
private String sentence;
public ServerConnection(Socket connection, String clientSentence){
serverConnection = connection;
sentence = clientSentence;
}
#Override
public void run() {
Random r = new Random();
String substring = sentence.substring(0, r.nextInt(sentence.length()));
try {
OutputStream os = serverConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(substring);
bw.close();
out.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.
In the server you do a readLine(..), which means that it will wait for a end-of-line character.
But in your sender code, you just send a string with no line ending.
So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"
You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.
NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.

Continuous data sending and receiving [duplicate]

This question already has answers here:
Java Socket why server can not reply client
(4 answers)
Closed 3 years ago.
I'm very new to socket programming. I have a requirement on continuously sending and receiving data between client and server. Below the process flow needs to be done.
Client sends "Client Hello" message to Server.
Server sends "Server hello" message to Client.
Client Sends "What is your server id?" message to Server
Server sends "My ID is #1" message to Client.
Client sends "Thank you" message to Server.
Server send "You are welcome" message to client
I tried to do this using Java sockets API. But i can't send multiple messages using a one socket. only 1 and 2 messages were able to transmit. Can someone tell me a way to achieve this requirement? Highly appreciate if someone give me an advise on this.
This is the server side program
package socketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer{
public static void main(String args[]){
final int SocketServerPORT = 4000;
try{
ServerSocket serverSocket = new ServerSocket(SocketServerPORT);
System.out.println("Server is started with port"+ serverSocket.getLocalPort());
System.out.println("Waiting for connection...");
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Receiving Client Hello
System.out.println(input.readLine());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//Sending Server Hello
output.write("Server Hello");
output.flush();
//Recieving Client message asking regarding Server ID
System.out.println(input.readLine());
//Sending Server ID to client
output.write("MY Server ID is #1");
output.flush();
//Recieving Client Thank you message
System.out.println(input.readLine());
//Sending Welcome message to Client
output.write("You are welcome.");
output.flush();
output.close();
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the Client Side program
package socketclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
final int socketServerPORT = 4000;
final String host="127.0.0.1";
try {
Socket clientSocket=new Socket(host,socketServerPORT);
PrintWriter output = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
//Sending Client Hello
output.println("Client Hello");
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Receiving Server Hello
System.out.println(input.readLine());
//Asking for Server ID
output.println("What is your Server ID");
output.flush();
//Receving Server ID
System.out.println(input.readLine());
//Sending Thank you message to Server
output.println("Thank you.");
output.flush();
//Receving Welcome message from Server
System.out.println(input.readLine());
output.close();
input.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You are reading lines but you aren't writing lines. The readLine() method blocks until a line terminator or end of stream occurs. You need to either append \n to each message or use println() instead of write().

Categories

Resources