我正在尝试编写一个简单的服务器-客户端程序,但我有一个问题:我可以从客户端向服务器发送数据,但不能从服务器发送数据(我不能在客户端接收数据) :(
那么如何从服务器发送数据,并在客户端接收数据呢?
服务器:
//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) {}
}(很抱歉代码太长了)
提前谢谢你。
发布于 2009-04-12 13:28:11
您的服务器的OutputStream是一个PrintStream,但是您的客户机的InputStream是一个DataInputStream。尝试将服务器更改为使用与客户端类似的DataOutputStream。
更好的做法是同时使用PrintWriter和BufferedReader,就像Sun's Socket Tutorial中的示例客户机/服务器对一样。
简单解释一下你的代码为什么不能工作:你可以把Stream对象看作是你的数据通过的过滤器。筛选器会更改您的数据,对其进行格式化,以便另一端的匹配筛选器能够理解它。当您通过一种类型的OutputStream发送数据时,您应该使用匹配的InputStream在另一端接收数据。
正如您不能将String对象存储在double中,或将double存储在String中(不是在不转换它的情况下),您也不能将数据从一种类型的OutputStream (在本例中为PrintStream)发送到另一种类型的InputStream。
发布于 2009-04-13 17:20:54
我认为另一个问题是我没有在文本后发送"\n“,但我使用了readLine()方法。
发布于 2009-04-13 18:06:29
在os.write()之后执行os.flush();消息非常小,可能因为它没有填满缓冲区而没有被发送。
https://stackoverflow.com/questions/741753
复制相似问题