1

我有以下用于向服务器发送字符串的客户端套接字。服务器没有收到消息。可能是什么问题?

public void startClient() throws IOException {

    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    InetAddress host = null;
    BufferedReader stdIn = null;

    try {
        host = InetAddress.getByName("172.16.2.97");
        socket = new Socket(host, 52000);

        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser = null;
        //ClientHelper.unpackISO();
        fromUser = ClientHelper.createISO();
        if (fromUser != null) {
            //System.out.println("Client - " + fromUser);
            out.write(fromUser);
            System.out.println("Sent message");
        }


        while ((fromServer = in.readLine()) != null) {
            System.out.println("Server - " + fromServer);
            if (fromUser != null) {
                //System.out.println("Client - " + fromUser);
                out.println(fromUser);
            }
        }
    } catch (ISOException ex) {
        Logger.getLogger(ClientDemo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownHostException e) {
        System.err.println("Cannot find the host: " + host.getHostName());
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't read/write from the connection: " +            e.getMessage());
        System.exit(1);
    } finally { //Make sure we always clean up
        out.close();
        in.close();
        stdIn.close();
        socket.close();
    }
}

ClientHelper.createISO() 方法返回一个应该发送到服务器的字符串。不幸的是,服务器没有得到任何字符串。问题可能是代理设置。如果是这样怎么解决。还是我的代码有另一个问题?我的代码有什么问题?

4

2 回答 2

1

检查下面的第 5 行,您需要刷新输出流。否则服务器将不会收到任何数据包,并且您将卡在第一个 in.readLine() 上,因为它会阻塞。

    fromUser = ClientHelper.createISO();
    if (fromUser != null) {
        //System.out.println("Client - " + fromUser);
        out.write(fromUser);
        out.flush(); // FLUSH IT HERE, packet wont be sent until you flush your stream
        System.out.println("Sent message");
    }

还要在循环内的 out.write(fromUser) 之后添加刷新。

于 2013-04-30T11:46:22.817 回答
1

写入流后,您必须刷新()流。套接字缓冲,直到你得到一个完整的数据包,否则

于 2013-04-30T11:17:23.773 回答