套接字中的麻烦

时间:2011-04-11 05:30:33

标签: java sockets bufferedreader java-server

当我启动服务器和客户端时,服务器无法接收客户端中输入的单词。 我希望服务器显示来自客户端的消息。但服务器似乎挂在“bf.readLine()”上。我不知道为什么...... 遵守守则......

服务器代码:

ServerSocket ss = new ServerSocket(11111);
System.out.println("current port:"+ss.getLocalPort());
Socket s = ss.accept();

System.out.println("remote port:"+s.getPort());

BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

while(true)
{
    String str = bf.readLine();
    System.out.print(s.getPort()+": ");
    System.out.println(str);
    if ("bye".equals(str))
        break;
}

然后是客户端代码:

Socket s = new Socket("127.0.0.1",11111);
System.out.println("connected to remote server:"+s.getPort());
System.out.println("My port:"+s.getLocalPort());

PrintWriter pw = new PrintWriter(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

Scanner in = new Scanner(System.in);

while (true)
{
    System.out.print("I said: ");
    String l = in.next();

    pw.write(l);
    pw.flush();
    System.out.println("Echo~~~~"+l);
}

1 个答案:

答案 0 :(得分:4)

您使用write()编写字节,但使用readln()读取。 Readln最后需要“\ n”。