- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.UnknownHostException;
- public class TCPDemo {
- public static void main(String[] args) {
- class Server{
- private ServerSocket mServer;
- private Socket mClient;
-
-
- public void begin() throws IOException{
- mServer = new ServerSocket(60000);
- mClient = mServer.accept();
-
- mClient.getOutputStream().write("nihao".getBytes());
- System.out.println("server send over");
-
- mClient.close();
- mServer.close();
- System.out.println("server over");
- }
- }
- class Client{
- private Socket mClient;
-
- public void begin() throws UnknownHostException, IOException, InterruptedException{
- mClient = new Socket("127.0.0.1", 60000);
- Thread.sleep(3000);
- System.out.println("Client recevice data");
-
- System.out.println(mClient.getInputStream().read());
- }
- }
-
- new Thread(new Runnable(){
- @Override
- public void run() {
- try {
- new Server().begin();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- }).start();
-
- new Thread(new Runnable(){
- @Override
- public void run() {
- try {
- new Client().begin();
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- }).start();
- }
-
-
- }
复制代码 我的思路是这样的。 开启了 服务器 和客户端。 客户端 连接上服务器, 服务器在 连接之后,会给 客户端发送 数据,然后关闭。而 客户端 连接上了 之后, sleep 3s 再接收数据。我的 问题是 ,客户端 sleep 醒来之后, 服务器 早就 关闭了 连接,那为什么
客户端还能从 流中 读取数据。
|