Java套接字问题

Jan*_*ani 1 java sockets

我正在尝试编写一个简单的服务器 - 客户端程序,但我遇到了一个问题:我可以将数据从客户端发送到服务器,但我无法从服务器发送数据(我无法在客户端中收到它): (
那么如何从服务器发送数据,并在客户端中重现它?

服务器:

//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();
}
Run Code Online (Sandbox Code Playgroud)

客户:

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) {}
}
Run Code Online (Sandbox Code Playgroud)

(对不起长代码)
提前谢谢.

Bil*_*ard 7

您的服务器的OutputStream是一个PrintStream,但您的客户端的InputStream是一个DataInputStream.尝试更改服务器以使用与客户端类似的DataOutputStream.

更好的方法是更改​​两者以使用PrintWriter和BufferedReader,就像Sun的Socket Tutorial中的示例客户端/服务器对一样.


只是解释一下为什么你的代码不起作用:你可以将Stream对象想象成数据通过的过滤器.过滤器会更改您的数据,对其进行格式化,以便另一端的匹配过滤器可以理解它.当您通过一种类型的OutputStream发送数据时,您应该在另一端使用匹配的InputStream接收它.

就像你不能将String对象存储在一个双字符串中,或​​者在一个字符串中存储一个double(不是没有转换它),你不能将数据从一种类型的OutputStream(在这种情况下是一个PrintStream)发送到另一种类型的的InputStream.