我正在开始客户端 - 服务器编程。我想要做的基本上是一个Echo服务器,但不是返回与插入客户端相同的东西,我希望服务器返回2 *(我插入的数字)。
我有以下服务器:
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;
}
}
}
}
以下客户:
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);
}
}
}
有人可以帮忙吗?
我在服务器端遇到以下错误:
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)
当我插入一个值(在这种情况下为'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)
谢谢
答案 0 :(得分:2)
答案 1 :(得分:1)
在将结果发送回之前有一个无限循环 客户端。
while(dis != null) {
int res = dis.read();
total = 2*(res);
}
dos.writeInt(total);
将最后一行移到括号内,它应该有效。
while(dis != null) {
int res = dis.read();
total = 2*(res);
dos.writeInt(total);
}
此外,无需调用client.shutdownOutput()
。您
当你下次尝试写信时会出现异常:
Disables the output stream for this socket. For a TCP socket, any previously written data will be sent followed by TCP's normal
连接终止序列。如果您写入套接字输出 在套接字上调用shutdownOutput()之后流,流将 抛出IOException。 `
然后还有前面提到的问题:
int res = dis.read();
应该是
int res = dis.readInt();
您在客户端读取用户输入时遇到类似问题。 请改用:
int fromClient = Integer.parseInt(input.readLine());