码迷,mamicode.com
首页 > 编程语言 > 详细

Java 网络编程

时间:2017-09-07 00:48:42      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:ann   const   logs   amr   output   默认   阻塞   stack   代码   

1. Socket 编程原理

网络上的实体通过端到端的连接进行数据的发送与接收,即进行通信。通信的一端就叫做一个socket。要通过socket进行通信,服务端和客户端都需要为通信做一些准备。

首先,服务端需要初始化socket,然后为socket绑定端口和IP,客户端使用这个IP和端口表名要与哪个服务端进行通信。

然后,服务端对socket进行监听

客户端需要初始化socket,绑定要连接的服务端的IP和端口,系统也会为客户端分配默认的IP和端口

  这时如果客户端调用connet()函数,就会发送建立连接的请求到服务端,服务端此时如果正在监听这个socket,并且监听到了这个请求,就会调用accept()接收这个请求,然后告诉客户端已经收到了它的建立连接的请求,阻塞在accept()上,这时客户端发送ACK到服务端connect()返回。服务器收到这个ACK,连接建立,accept()返回。socket连接在通信双方建立起来,双方都可以通过write()和read()进行数据的发送与接收。

  具体原理如下图所示:

  技术分享

 

 

2. Java的socket编程实例

  (1) 客户端代码

  

 1 import java.io.BufferedReader;
 2 import java.io.BufferedWriter;
 3 import java.io.IOException;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStreamWriter;
 6 import java.net.Socket;
 7 import java.net.UnknownHostException;
 8 /*
 9  * inputReader.readLine()读取的字符串没有加上"\n",所以服务端调用readLine读取的时候,没有读到"\n"于是阻塞;
10  * eclipse的显示平台混乱
11  */
12 public class Client {
13     Socket socket;
14 
15     public static void main(String[] args) {
16         // TODO Auto-generated method stub
17         Client client = new Client();
18         try {
19             client.runClient();
20         } catch (UnknownHostException e) {
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         } catch (IOException e) {
24             // TODO Auto-generated catch block
25             e.printStackTrace();
26         }finally{
27             try {
28                 client.socket.close();
29             } catch (IOException e) {
30                 // TODO Auto-generated catch block
31                 e.printStackTrace();
32             }
33         }
34     }
35     public void runClient() throws UnknownHostException, IOException{
36         //Scanner outScanner = new Scanner(System.in);
37         Socket socket = new Socket("127.0.0.1", 40004);
38         this.socket = socket;
39         System.out.println("客户端连接到"+socket.getRemoteSocketAddress());
40         BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
41         BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
42         BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
43         String inString = "";
44         String string = inputReader.readLine();
45         while (string != null) {
46             socketWriter.write(string);
47             socketWriter.write("\n");
48             socketWriter.flush();
49             System.out.println("客户端发送"+string);
50             if(string.equals("bye")){
51                 break;
52             }
53             inString = socketReader.readLine();
54             System.out.println("客户端收到:" + inString);
55             string = inputReader.readLine();
56             //inString = socketReader.readLine();
57         }
58         System.out.println("客户端结束");
59         socket.close();
60     }
61 
62 }

(2) 服务端代码

 1 /*
 2  * 一个套接字接口构成一个连接的一端,可以对它进行读写,读写之前要先打开,结束读写之后要进行关闭
 3  * 1. 服务器端打开socket的过程如下
 4  *      IP和Port可以唯一的确定一端,所以通过ip和port初始化socket,通过bind()
 5  *      listen()进行监听
 6  *      accept()等待客户端的请求,然后创建连接
 7  *      write()
 8  *      read()
 9  * 2. 通过使用线程为多个客户端进行服务
10  *      
11  */
12 import java.io.BufferedReader;
13 import java.io.BufferedWriter;
14 import java.io.IOException;
15 import java.io.InputStreamReader;
16 import java.io.OutputStreamWriter;
17 import java.net.ServerSocket;
18 import java.net.Socket;
19 
20 public class Server {
21 
22     public static void main(String[] args) {
23         // TODO Auto-generated method stub
24         Server server = new Server();
25         server.runServer();
26     }
27     public void runServer(){
28         ServerSocket serverSocket = null;
29         try {
30             serverSocket = new ServerSocket(40004);
31             while (true) {
32                 Socket socket = serverSocket.accept();
33                 DisposeThread runnable = new DisposeThread(socket);
34                 Thread thread = new Thread(runnable);
35                 thread.start();
36             }
37         } catch (IOException e) {
38             // TODO Auto-generated catch block
39             e.printStackTrace();
40         }finally{
41             try {
42                 if(serverSocket != null){
43                     serverSocket.close();
44                 }
45             } catch (IOException e) {
46                 // TODO Auto-generated catch block
47                 e.printStackTrace();
48             }
49         }
50     }
51     class  DisposeThread implements Runnable{
52         Socket socket;
53         public  DisposeThread(Socket socket) {
54             // TODO Auto-generated constructor stub
55             this.socket = socket;
56         }
57         @Override
58         public void run() {
59             // TODO Auto-generated method stub
60             try {
61                 BufferedReader readerSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
62                 BufferedWriter writerSocket = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
63                 String string = readerSocket.readLine();
64                 while (string != null) {
65                     System.out.println("服务端收到:" + string);
66                     if(string.equals("bye")){
67                         break;
68                     }
69                     writerSocket.write(string+"\n");    
70                     writerSocket.flush();
71                     string = readerSocket.readLine();
72                 }
73                 socket.close();
74             } catch (IOException e) {
75                 // TODO Auto-generated catch block
76                 e.printStackTrace();
77             }finally{
78                 try {
79                     socket.close();
80                 } catch (IOException e) {
81                     // TODO Auto-generated catch block
82                     e.printStackTrace();
83                 }
84             }
85         }
86         
87     }
88 
89 }

 

Java 网络编程

标签:ann   const   logs   amr   output   默认   阻塞   stack   代码   

原文地址:http://www.cnblogs.com/starlight93/p/7487657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!