I have been working with socket programming. I was trying to develop a two way communication from server to client. The data is being received when sent from server to client but there is a problem when I am sending from client to server.
I am getting an error as "Socket is closed" pointing to the line where I have created a BufferedReader. I have simplified some part of my code to be very specific.
Kindly find the code attached.
import java.io.*; import java.net.*; import java.util.*; public class Server { public static void main(String args[]) { String id="policeone"; int hashcodeid=0; try { ServerSocket srvr=new ServerSocket(1234); Socket client=srvr.accept(); System.out.println("Connected to a client"); PrintWriter out=new PrintWriter(client.getOutputStream(),true); // code to perfrom operations.. out.print(id+" "); out.print(hashcodeid+" "); //out.print(x); out.print(message1+" "); //sending data to client working... no problem. // reading data form client... throwing exception.. "Socket is closed" BufferedReader fromserver=new BufferedReader(new InputStreamReader(client.getInputStream())); while(!fromserver.ready()){} String nowstring=fromserver.readLine(); System.out.println("Received from client "+nowstring); } catch(Exception e) { e.printStackTrace(); } } }
import java.io.*; import java.net.*; import java.util.*; public class Client { public static void main(String args[]) { try{ String id="vehicle1"; String idstring,hash,allstring; int hashcodeid2=0; Socket skt = new Socket("localhost", 1234); BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); System.out.print("Received string: '"); while (!in.ready()) {} //code to read and manipulate data from server BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter toserver=new PrintWriter(skt.getOutputStream(),true); toserver.print("helo"); //no problem in client.. server throwing exception at this point. } catch(Exception e) { e.printStackTrace(); } } }
error::
Receiving string from client: 'java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:872)
at Server.main(Server.java:51)