从套接字读取时返回Null字符串

时间:2015-12-07 16:12:01

标签: java sockets tcp-ip

我正在尝试使用tcp / ip连接到服务器。

我能够连接到服务器,但我得到的响应为null。

CODE

 import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;

    public class Client {
        private static final String SERVER_ADDRESS = "192.168.64.79";
        private static final int TCP_SERVER_PORT = 6669;

        public void connect() {
            BufferedReader in;
            try {
                // Socket skt = new Socket("50.128.128.254", 6669);//ip,port
                Socket clientSocket = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);// ip,port

                System.out.println(" client Socket created ..Enter input : ");
    //          BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

                PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);

                String ToServer = "123";//inFromUser.readLine();
                outToServer.println(ToServer);

                 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


                System.out.print("Received string: \n");

        //          while (!in.ready()) {
        //          }

// in is never ready
                    System.out.println(in.readLine()); // NULL returned

        //          System.out.print("'\n");
                    in.close();
                    System.out.print("connection closed");

                } catch (Exception e) {
                    System.out.print("Whoops! It didn't work!\n");
                    e.printStackTrace();
                }

            }

        }

我已提到Getting Null String when reading from a socket

修改 有时我会得到空响应,有时我会遇到连接重置错误(同样的输入也是如此)

java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at Tcp.Client.connect(Client.java:33)
    at Pms.main(Pms.java:8)

谢谢

0 个答案:

没有答案