我正在尝试编写一个简单的服务器-客户端程序,但我遇到了一个问题:
我可以从客户端向服务器发送数据,但我不能从服务器发送数据(我不能在客户端接收它):(
那么如何从服务端发送数据,并在客户端接收呢?
服务器:
//this is in a thread
try {
server = new ServerSocket(1365);
} catch (IOException e) {
e.printStackTrace();
}
while (!exit) {
try {
clientSocket = server.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
while ((line = is.readLine()) != null) {
System.out.println("Message from client: " + line);
//if (line.equals("exit")) {
// exit = true;
//}
if (line.equals("say something")) {
os.write("something".getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
os.close();
}
客户:
try {
socket = new Socket(host, 1365);
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {}
if (socket != null && os != null && is != null) {
try {
os.writeBytes("say something");
//get the answer from server
os.close();
is.close();
socket.close();
} catch (IOException e) {}
}
(抱歉代码太长)
提前谢谢你。
最佳答案
您的服务器的 OutputStream 是一个 PrintStream,但您的客户端的 InputStream 是一个 DataInputStream。尝试更改服务器以像您的客户端一样使用 DataOutputStream。
更好的方法可能是同时使用 PrintWriter 和 BufferedReader,就像 Sun's Socket Tutorial 中的示例客户端/服务器对一样.
稍微解释一下为什么您的代码不起作用:您可以将 Stream 对象视为数据通过的过滤器。过滤器会更改您的数据,对其进行格式化,以便另一端的匹配 过滤器可以理解它。当您通过一种类型的 OutputStream 发送数据时,您应该在另一端使用匹配的 InputStream 接收它。
正如您不能将 String 对象存储在 double 中,或将 double 存储在 String 中(不是不转换它),您也不能将数据从一种类型的 OutputStream(在本例中为 PrintStream)发送到不同类型的 InputStream。
关于Java套接字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/741753/