ChenZhK 2016-07-17 07:38 采纳率: 50%
浏览 1092
已结题

在本机上模拟网络聊天,用Socket进行网络通信的疑问。求大神帮忙解答。

package day23;
import java.io.*;
import java.net.*;
class TcpClient2
{
public static void main(String[] args)throws Exception
{
Socket s = new Socket("192.168.1.102",10004);

    OutputStream out = s.getOutputStream();

    out.write("服务端,你好".getBytes());


    InputStream in = s.getInputStream();

    byte[] buf = new byte[1024];

    int len = in.read(buf);

    System.out.println(new String(buf,0,len));

    s.close();
}

}

class TcpServer2
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10004);

    Socket s = ss.accept();

    String ip = s.getInetAddress().getHostAddress();
    System.out.println(ip+"....connected");
    InputStream in = s.getInputStream();

    byte[] buf = new byte[1024];

    int len = in.read(buf);

    System.out.println(new String(buf,0,len));


    OutputStream out = s.getOutputStream();


    Thread.sleep(10000);
    out.write("哥们收到,你也好".getBytes());

    s.close();

    ss.close();
}

}
//先运行服务端TcpServer2,此时因为accept()而阻塞,再运行客户端TcpClient2,客户端和服务端都使用getInputStream方法,获取了读取流in,为什么客户端没有读取到“服务端,你好”并打印?而服务端却读取到了?代码一模一样啊。菜鸟一枚,请大神指点,谢谢。

  • 写回答

7条回答

  • 詹詹自喜KING 2016-07-17 10:46
    关注

    服务端的导包你这里是省略了是吧?代码没什么问题,正常运行,结果正常。你可以试试重启一下软件,对代码进行剪切粘贴然后重新运行。

    评论

报告相同问题?