I’m beginning client-server programming. what I’m trying to do is basically a Echo server but instead of return the same thing as the client inserted, I want the server to return 2*(The number I insert).
I have the following server:
public class Server {
public static void main(String args[]) throws Exception {
ServerSocket server = new ServerSocket(6789);
while(true) {
try {
Socket aux = server.accept();
DataInputStream dis = new DataInputStream(aux.getInputStream());
DataOutputStream dos = new DataOutputStream(aux.getOutputStream());
int total = 0;
while(dis != null) {
int res = dis.read();
total = 2*(res);
dos.writeInt(total);
}
}
catch (EOFException e) {
out.println("The client exit!");
continue;
}
}
}
}
And the following client:
public class Client {
public static void main(String args[]) throws Exception {
Socket client = new Socket("localhost", 6789);
DataInputStream dis = new DataInputStream(client.getInputStream());
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(in));
while(true) {
int fromClient = input.read();
dos.writeInt(fromClient);
client.shutdownOutput(); //to show to the server the end of file
int fromServer = dis.readInt();
out.println(fromServer);
}
}
}
Can somebody help please?
I got the following error on the server side:
Exception in thread "main" java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:132)
at java.io.DataOutputStream.writeInt(DataOutputStream.java:197)
at Server.main(Exercicio3.java:21)
And on the client side when I insert a value (in this case ‘1’):
1
0
Exception in thread "main" java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:132)
at java.io.DataOutputStream.writeInt(DataOutputStream.java:197)
at Client.main(Exercicio4.java:25)
Thanks
There is an infinite loop before you send the result back to the
client.
Move that last line inside the brackets and it should work.
Additionally, calling
client.shutdownOutput()is not necessary. Youwill just get exceptions when you try to write to it the next time:
connection termination sequence. If you write to a socket output
stream after invoking shutdownOutput() on the socket, the stream will
throw an IOException. `
And then there is also the issue mentioned previously:
should be
You have a similar issue reading the user’s input in the client.
Use this instead: