- import java.io.*;
- import java.net.*;
- class ClientDemo
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("127.0.0.1",10002);
- DataOutputStream out =new DataOutputStream(s.getOutputStream());
- out.write("TCP 来了".getBytes());
- DataInputStream in = new DataInputStream(s.getInputStream());
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- String text = new String(buf,0,len);
- System.out.println("server:"+text);
- s.close();
- }
- }
- class ServerDemo
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10002);
- Socket s = ss.accept();//该方法是阻塞式的。
-
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+".....connected");
- DataInputStream in = new DataInputStream(s.getInputStream());
- byte[] buf = new byte[1024];
- int len = 0;
- while(( len = in.read(buf))!=-1);
- {
- String text = new String(buf,0,len);
- System.out.println(text);
- }
- DataOutputStream out =new DataOutputStream(s.getOutputStream());
- out.write("已收到".getBytes());
- s.close();
- ss.close();
- }
- }
复制代码 开启服务端,运行客户端以后,程序阻塞了,收不到服务器端发来的信息
程序运行结果:
这个方法为什么会阻塞?可否解答一下?谢谢了。
|