I got here client and server side programs. Client talks to server by sending a string, the server then converts the string into capital letters and sends back. The problem is that the client does not receive any string from the server. Only the server prints 2 passed in strings, then the server throws IOException. I guess that because client closed connection. But why does client does not receive any message from server? How to overcome this issue?
Thanks
Client:
package solutions;
import java.io.*;
import java.net.*;
class SocketExampleClient {
public static void main(String [] args) throws Exception {
String host = "localhost"; // hostname of server
int port = 5678; // port of server
Socket s = new Socket(host, port);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("Hello World!");
System.out.println(dis.readUTF());
dos.writeUTF("Happy new year!");
System.out.println(dis.readUTF());
dos.writeUTF("What's the problem?!");
System.out.println(dis.readUTF());
}
}
Server:
package solutions;
import java.io.*;
import java.net.*;
class SocketExampleServer {
public static void main(String [] args) throws Exception {
int port = 5678;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting incoming connection...");
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String x = null;
try {
while ((x = dis.readUTF()) != null) {
System.out.println(x);
dos.writeUTF(x.toUpperCase());
}
}
catch(IOException e) {
System.err.println("Client closed its connection.");
}
}
}
Output:
Waiting incoming connection...
Hello World!
Happy new year!
What's the problem?!
Client closed its connection.
Your main program is exiting before it has a chance to read the response from the server. If you add the following code it will work fine. 🙂 UPDATE- I just realised your code is working fine on my computer – and it does output the string as expected. DataInputStream.readUTF() is blocking correctly and receiving the response. Are you still having the problem?