What time to close socket connection in Java - 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.

Related

Reading message fails if client not inside a while loop

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.

Why TCP/IP server with listening port in java not working

I have written a code in java to interface my computer with a transmitter a transmitter device, with a communication board already implemented and ready to connect via TCP/IP to any server with a specific address IP (say 192.168.2.2) and listening to a specific port number (say 4000).
I followed the exact strep how to create a server side application in Java offering a that listening port, so that I can connect to that transmitter.
I don't understand why when I try to debug the code, it blocks a the line clientSocket = serverSocket.accept(), and throws a timeout exception.
Could someone help me find out where the error might be in my code?
Any help would be greatly appreciated.
Thanks.
Here is the code:
public class Server {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Declares server and client socket, as well as the input and the output stream
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out;
//BufferedReader in;
BufferedReader in;
try{
InetAddress addr = InetAddress.getByName("192.168.2.2");
//Opens a server socket on port 4000
serverSocket = new ServerSocket(4000) ;
//Sets the timeout
serverSocket.setSoTimeout(30000);
System.out.println("Server has connected");
//Create a connection to server
System.out.println("Server listening connection from client ....");
//Listens and waits for client's connection to the server
clientSocket = serverSocket.accept();
// Creates input and output streams to socket
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Reads response from socket
while((in.readLine())!= null ){
System.out.println ( in.readLine() );
}
System.out.println ( "Closing connection ....");
//Terminates connection
clientSocket.close();
serverSocket.close();
System.out.println("Connecton successfully closed");
}
catch(IOException e){
System.out.println(e);
}
}
}
Could someone help me find out where the error might be in my code?
There is no error in your code that could cause this problem. Clearly you haven't configured the device to connect to this server correctly, or the device isn't running, or it isn't connecting, or there is a firewall in the way. Investigate that.
However:
InetAddress addr = InetAddress.getByName("192.168.2.2");
What is this for? It isn't used.
System.out.println("Server has connected");
This is simply not true. The server hasn't connected. At this point all it has done is create a listening socket.
while((in.readLine())!= null ){
Here you are reading a line and throwing it away.
System.out.println ( in.readLine() );
Here you are printing every second line, having thrown every odd line away. The correct way to write this loop is:
String line;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
Note also that this server will service exactly one client and then exit. There should be a loop around everything from accept() to clientSocket.close(), and if there are multiple devices it should start a new thread per accepted socket to handle the I/O.
You specified timeout of 30 seconds, didn't you? :
serverSocket.setSoTimeout(30000);
So after 30 seconds, no matter whether stopped in debugger or running, this will timeout and throw exception.

Java socket hanging when inside of java servlet

So I've been trying to figure out how to send messages between my arduino and my java servlet (tomcat) and have been bumping into some problems. I'm using this code in my java servlet:
ServerSocket server;
//socket server port on which it will listen
int port = 9876;
String message = "";
//create the socket server object
server = new ServerSocket(port);
System.out.println("Server socket created");
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request...");
//creating socket and waiting for client connection
Socket socket = server.accept();
BufferedReader buff = new BufferedReader(new InputStreamReader (socket.getInputStream()));
System.out.println("Input stream established");
message = buff.readLine();
System.out.println("Message Received: " + message);
buff.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
But it's hanging on the
Socket socket = server.accept();
line. I assume this is because the messages i'm sending from the arduino aren't arriving. On the arduino side of things, this is my client:
if (client.connect(ip, 9876)) {
Serial.println("connected");
client.println("12345678");
Serial.println("Message sent");
} else {
Serial.println("connection failed");
}
Not much to it. Now, I've tried sending this as a HTTP POST request, but without success (surely i'm doing it incorrectly, i just don't know how to do it, i've tried for a while). I know this is probably horrifically written, but i'm very open to learning from you guys today.
The weird thing is that this works exactly how i want it to when i put the java server code in a new regular java project. Can anyone help me figure this out? Why is it hanging in the servlet but not in a regular java project?

My java chat client only sends strings when the dataStream is closed

I created a java chat application (client and server)
Everything works fine when I'm on my LAN (using LAN IP address of the server into my client).
But when I'm using the Internet address of my server in my client, the strings are sent only when I close the output Data stream of my client (and all the strings are sent at once).
Here's a quick snap of my code (I have port forward from 6791 to 6790 in the example below),
My server (thread):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
My client:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
I've tried with DataOutStreams, there's nothing to do.
My server will only receive the strings when out.close() is called on client side.
Is there a reason why, over the Internet, the data stream has to be closed for data to be sent? Is there a way around this? Am I doing something wrong?

Does closing the inputstream of a socket also close the socket connection?

In Java API,
Socket socket = serverSocket.accept();
BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toSocket = new PrintWriter(socket.getOutputStream());
//do sth with fromSocket ... and close it
fromSocket.close();
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();
In the above code, after I close the InputStream fromSocket, it seems that the socket connection is not available anymore--the client wont receive the "is socket connection still available" message.
Does that mean that closing the inputstream of a socket also closes the socket itself?
Yes, closing the input stream closes the socket. You need to use the shutdownInput method on socket, to close just the input stream:
//do sth with fromSocket ... and close it
socket.shutdownInput();
Then, you can still send to the output socket
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();

Categories