Java Socket不向服务器发送消息

时间:2013-04-30 11:09:04

标签: java socket.io

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

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()方法返回一个应该发送到服务器的字符串。不幸的是服务器没有得到任何字符串。问题可能是代理设置。如果是这样,怎么解决它。或者这是我的代码的另一个问题? 我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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)之后添加flush。