I am not able to send the data on the second instance. The server just waits infinitely for client data
Here is my sample server code snippet:
ServerSocket serv = new ServerSocket(6789);
Socket soc = serv.accept();
System.out.println("waiting for client's input");
BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
DataOutputStream out = new DataOutputStream(soc.getOutputStream());
String indata=in.readLine();
System.out.println("The client says: "+indata+"\n Send them some data: ");
String datum="demodata";
out.writeBytes(datum);
System.out.println("Data sent");
Sample Client:
ocket soc = new Socket("localhost",6789);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
DataOutputStream out = new DataOutputStream(soc.getOutputStream());
System.out.println("Connected to: "+soc.getLocalAddress() +"\nEnter data to be sent: ");
String outdata = br.readLine(); //take input
out.writeBytes(outdata); // send
String indata=in.readLine(); //read
System.out.println("Data Sent! Now reading data from server "+indata)
Please tell me my problem! Thanks in advance
Answer is quite simple. You want to exchange lines of text between server and client.
The correct part is on the server side:
The wrong part is on the client side:
I haven’t tested the code, but it seems you are just sending some data and your server side waits for
\n(newline escape sequence) to appear.Option 1:
Construct a
PrintWriterand call the correspondingprintlnmethod.Option 2:
Append a newline (
\n) manually.Afterwards,
readLineon the server side will recognize the line terminated by\nand will proceed.