Reading message fails if client not inside a while loop - java

I have a small TCP server and client where the server is performing inside a while(true) loop meanwhile my client isn't. However when i send a message from the client to the server, the server isn't able to read it. Below is the code and error:
SERVER:
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("[SERVER]: Server launched on port " + port);
while (true) { // the while loop makes the server continuously accept client request
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println(reader.readLine());
}
CLIENT:
Socket socket = new Socket("localhost", 9101);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("lol");
ERROR:
Exception in thread "main" java.net.SocketException: Connection reset
The error occurs when we try to read data in the server. With all that being said, if i surround the out.println() method in the client in a while(true) loop the error goes away and the code works fine. So i'm wondering why the i get this exception when the server is inside an infinite loop but the client isn't.

Related

Client connects twice when using Postman to send requests?

I'm trying to create a server in Java using Sockets. I create a ServerSocket using ServerSocket serverSocket = new ServerSocket(port); and then attempt to connect using Socket clientSocket = serverSocket.accept();. I send the request through Postman.
My issue is that whenever I send a request, I get the output:
New client connected
input: null
closed!
New client connected
input: PUT / HTTP/1.1
closed!
I'm confused as to why the client connects twice, and why the first request is always empty.
Full code:
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
BufferedReader br = new BufferedReader(new InputStreamReader((clientSocket.getInputStream())));
String input = br.readLine();
System.out.println("input: " + input);
clientSocket.close();
System.out.println("closed!");
}

Bug when create new Thread for a Socket

I'm using this code to constantly accept when a new Socket connect to Server:
while (true) {
Socket socket = null;
socket = ss.accept();
System.out.println("A client is connect...\n");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Thread acceptClient = new Thread(new ClientHandler(socket, in, out));
acceptClient.start();
}
But when a connection is created, I see this in the console:
A client is connect...
A client is connect...
A client is
connect...
I don't understand why this line is displayed 3 times. Can anyone explane?

What time to close socket connection in Java

Client
Socket socket = new Socket("ip", 5555);
PrintStream out = new PrintStream(socket.getOutputStream());
out.println("Hello Server!");
out.close();
socket.close();
Server
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
//keep listening
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = in.readLine();
System.out.println(line);
in.close();
socket.close();
}
if ignore concurrency issue, is the way to close sockets connection correct?
if ignore concurrency issue, is the way to close sockets connection correct?
Yes, but you don't need to close the socket if you've already closed the output stream.
if client closed socket immediately after sent data, will it cause some exception like 'socket is close' while server tries to read data from stream?
No. 'Socket is closed' means you closed the socket and then continued to use it. As long has the client has read everything the server is going to send, the client can close the socket: the server will read all the data the client has sent, and then get end-of-stream on the next read.

Client/Server Programming

I am practicing a simple java program where I am demonstrating simple client server interaction. The fist part of message from server gets transferred. Then program just continues to run and does not execute? Do we need to create a new socket for each individual traffic?
Server code
server = new ServerSocket(4587);
System.out.print("Starting the Server on port " + server.getLocalPort() + "\n");
System.out.println("Waiting for client...");
Socket client = server.accept();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader br1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
br.write("Hello, you are connected to Server. What is your name?");
br.write("\n");
br.flush();
while((s=br1.readLine())!=null)
{
}
br.write("Thank you ");
br.newLine();
br.flush();
}
Client code
String stdin;
System.out.println("Attempting to connect to " + hostname + ":" + port);
client = new Socket("localhost", 4587);
System.out.println("Connection Established");
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
BufferedWriter br1 = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
br1.write("Mike");
br1.write("\n");
br1.flush();
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
Server Output
Starting the Server on port4587
Waiting for client....
Client Output
Attempting to connect to :123
Connection Established
Hello you are connected to Server, What is ur name
If this could help..after this both loop
Your server will first create a connection with the client through the accept method. If you wish to have multiple clients you will need to change your code accordingly to accept that.
On the client side, you're using \n to delineate the end of a message. This will work fine. Every time you send a new message use \n to indicate the end of the message.
On the server side, you should continue reading from I/O until you see the \n. At that point you have received the entire message. Process it and than start listening again.
Edit:
Since you are waiting for the name of the client, you could simply do the following on the server:
BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader bin = new BufferedReader(new InputStreamWriter(client.getInputStream()));
// Wait for incoming name from client.
String name = bin.readline();
System.out.println(name);
// Send a reply.
bout.write("Thank you\n");
bout.flush();
Similarly, on the client (assuming bin and bout are defined the same as above):
// Send name to server.
bout.write("Name\n");
bout.flush();
// Get a response from the server and print to console.
String response = bin.readline();
System.out.println(response);
This is because BufferedReader has a default buffer = 8K when in reading process and this process is block I/O, so this will hang in that point. You should read the full message from client by server side.
Your problem is with the loop on the client side. It will be stuck in the loop as it waits to readlines sent from the server infinitely. (ie, after reading the first line from the server, it will expect more lines from the server and wait to read them).
To exit the loop you need to send an EOF signal or end of stream signal (according to the docs: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine%28%29)

client requesting from web server

I have coded a simple java client to send requests and receive data from my my java web server. The server is capable of handling persistent connections and everything works fine when I use browser to send requests however when I send requests using my client it only works with non persistent connections. when I use my java client to send requests it would receive the data requested from the server and then just freezes. My code for java client:
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO code application logic here
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter the file name that you would like to request from Server:");
sentence = inFromUser.readLine();
System.out.println("would you like to have a persistent connection (yes/no):");
String sentence1 = inFromUser.readLine();
if(sentence1.equals("yes")){sentence1="Connection: keep-alive";}
else{sentence1="Connection: close";}
outToServer.writeBytes("GET /"+sentence + "\r\n");
outToServer.writeBytes(sentence1+"\r\n");
outToServer.writeBytes("\r\n");
while ((modifiedSentence=inFromServer.readLine()) != null)
{
System.out.println("FROM SERVER: " + modifiedSentence);
}
System.out.println("done");
clientSocket.close();
}
My guess is that you try to modifiedSentence=inFromServer.readLine() after the server closed the connection (which closes the socket and the other streams as well) and you get a java.net.SocketException.
Try surrounding it with try/catch and print the error message / stacktrace

Categories