网络编程模型-java

1.我们做网络编程,先做一个模型出来再在模型的基础上加东西,就知道怎么回事了。

2.模拟服务器端代码

 1 import java.net.UnknownHostException;
 2 import java.net.InetAddress;
 3 import java.io.IOException;
 4 import java.net.ServerSocket;
 5 import java.net.Socket;
 6 import java.io.*;
 7 public class Address2 {
 8   
 9   public static void main(String[] args){
10    // try{InetAddress inetaddress=InetAddress.getByName("www.baidu.com");
11     //System.out.println(inetaddress);}catch(IOException e){  }
12     
13 
14 
15 
16 
17 
18 
19     //try{
20       
21     //  InetAddress inetaddress=InetAddress.getLocalHost();
22 
23     //  System.out.println(inetaddress);
24 
25 
26    //  }catch(IOException e){}
27 
28         
29   
30   try{
31       
32     
33    ServerSocket serversocket =new ServerSocket(8081); //端口号是自己随便写的
34      Socket socket=serversocket.accept();
35      OutputStream outputstream=socket.getOutputStream();
36      PrintWriter printwriter = new PrintWriter(outputstream);
37      printwriter.write("你好");
38      System.out.println("nihao");
39      printwriter.close();
40      outputstream.close();
41      socket.close();
42      serversocket.close();
43 
44 
45 
46 
47 
48 
49 
50 
51 
52      
53 
54 
55 
56     }catch(IOException e){}
57 
58 
59 }
60 }
61   

3.模拟客户端代码

 1 import java.net.UnknownHostException;
 2 import java.net.InetAddress;
 3 import java.io.IOException;
 4 import java.net.ServerSocket;
 5 import java.net.Socket;
 6 import java.io.*;
 7 public class Address {
 8   
 9   public static void main(String[] args){
10    // try{InetAddress inetaddress=InetAddress.getByName("www.baidu.com");
11     //System.out.println(inetaddress);}catch(IOException e){  }
12     
13 
14 
15 
16 
17 
18 
19     //try{
20       
21     //  InetAddress inetaddress=InetAddress.getLocalHost();
22 
23     //  System.out.println(inetaddress);
24 
25 
26    //  }catch(IOException e){}
27 
28         
29   
30   try{
31       
32     
33      InetAddress inetaddress=InetAddress.getLocalHost();
34      Socket socket =new Socket(inetaddress,8081);
35      socket.close();
36 
37 
38 
39 
40 
41 
42 
43 
44 
45      
46 
47 
48 
49     }catch(IOException e){}
50 
51 
52 
53 }
54   
55 
56 
57 
58 
59 }

4.先运行服务器端代码,你会发现光标一直闪烁。再另起命令窗口,执行客户端代码,你会发现服务器端窗口打印了字,说明服务器端接受到了客户端的会话。

 

5.客户端在建立soket对象时就向服务器端发送一个请求,服务器端接受到了请求,则进行某些操作。然后客户端可以接受到服务器端的操作结果。(两端的操作代码都是假设收到预定结果之后编写的)

6.标准模型

 

posted @ 2017-09-15 10:18  S-Mustard  阅读(262)  评论(0编辑  收藏  举报