1

尝试运行回显服务器时无法读取/写入数据到套接字。没有抛出异常,也没有对控制台输入的响应。代码中有什么不正确的地方?

public class Server {

    static ServerSocket server;

    public static void main(String[] args) throws IOException  {
        String hostname = "127.0.0.1";

        try{
            server = new ServerSocket(8888); 
          } catch (IOException e) {
            System.out.println("Could not listen on port 8888");
            System.exit(-1);
          }

        Socket theSocket = null;
        try {
            theSocket = new Socket(hostname, 8888);

            BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
            BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(theSocket.getOutputStream(), true);
            System.out.println("Connected to echo server");

            while (true) {
              String theLine = userIn.readLine();
              if (theLine.equals("."))
                break;
              out.println(theLine);
              out.flush();
              System.out.println("networkIn: "+networkIn.readLine());
            }
            networkIn.close();
            out.close();
            System.out.println("out.close();");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
4

2 回答 2

3

您创建了两个不相关的套接字,一个用于接受连接,一个用于连接到 (hostname,8888)。您需要调用accept()服务器套接字才能真正连接客户端。请参阅教程

于 2012-05-25T16:13:31.853 回答
1

首先添加Socket client = server.accept();. 然后你会看到你需要如何重组你的程序的其余部分。

于 2012-05-25T16:16:37.050 回答