在本机上模拟网络聊天,用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,为什么客户端没有读取到“服务端,你好”并打印?而服务端却读取到了?代码一模一样啊。菜鸟一枚,请大神指点,谢谢。

查看回复

相关问答