Socket的简单使用

一.Socket的概念
Socket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传输控制层之间的一组接口.

当两台主机通信是,必须通过Socket连接,Socket则利用TCP/IP协议建立TCP连接.TCP连接则更依赖于底层的IP协议.Socket是控制层传输协议.

双向的通信连接实现数据的交换,连接的一端成为一个Socket.

二.网络通信三要素
IP地址(网络上主机设备的唯一标识)
端口号(定位程序)
     有效端口:0~65535,其中0~1024由系统使用,开发中一般使用1024以上端口.
传输协议(用什么样的方式进行交互)
     常见协议:TCP(面向连接,提供可靠的服务),UDP(无连接,传输速度快)
三.Socket的通信流程


四.C#中Socket的简单使用步骤
第一步:服务端监听某个端口

第二步:客户端向服务端地址和端口发起Socket请求

第三步:服务器接收连接请求后创建Socket连接,并维护这个连接队列

第四步:客户端和服务端就建立起了双工同信,客户端与服务端就可以实现彼此发送消息

五.简单代码实例
1.服务端代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Net;
  5 using System.Net.Sockets;
  6 using System.Text;
  7 using System.Threading;
  8  
  9 namespace SocketUtil
 10 {
 11     public class SocketServer
 12     {
 13         private string _ip = string.Empty;
 14         private int _port = 0;
 15         private Socket _socket = null;
 16         private byte[] buffer = new byte[1024 * 1024 * 2];
 17         /// <summary>
 18         /// 构造函数
 19         /// </summary>
 20         /// <param name="ip">监听的IP</param>
 21         /// <param name="port">监听的端口</param>
 22         public SocketServer(string ip, int port)
 23         {
 24             this._ip = ip;
 25             this._port = port;
 26         }
 27         public SocketServer(int port)
 28         {
 29             this._ip = "0.0.0.0";
 30             this._port = port;
 31         }
 32  
 33         public void StartListen()
 34         {
 35             try
 36             {
 37                 //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
 38                 _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 39                 //2.0 创建IP对象
 40                 IPAddress address = IPAddress.Parse(_ip);
 41                 //3.0 创建网络端口,包括ip和端口
 42                 IPEndPoint endPoint = new IPEndPoint(address, _port);
 43                 //4.0 绑定套接字
 44                 _socket.Bind(endPoint);
 45                 //5.0 设置最大连接数
 46                 _socket.Listen(int.MaxValue);
 47                 Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString());
 48                 //6.0 开始监听
 49                 Thread thread = new Thread(ListenClientConnect);
 50                 thread.Start();
 51  
 52             }
 53             catch (Exception ex)
 54             {
 55             }
 56         }
 57         /// <summary>
 58         /// 监听客户端连接
 59         /// </summary>
 60         private void ListenClientConnect()
 61         {
 62             try
 63             {
 64                 while (true)
 65                 {
 66                     //Socket创建的新连接
 67                     Socket clientSocket = _socket.Accept();
 68                     clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));
 69                     Thread thread = new Thread(ReceiveMessage);
 70                     thread.Start(clientSocket);
 71                 }
 72             }
 73             catch (Exception)
 74             {
 75             }
 76         }
 77  
 78         /// <summary>
 79         /// 接收客户端消息
 80         /// </summary>
 81         /// <param name="socket">来自客户端的socket</param>
 82         private void ReceiveMessage(object socket)
 83         {
 84             Socket clientSocket = (Socket)socket;
 85             while (true)
 86             {
 87                 try
 88                 {
 89                     //获取从客户端发来的数据
 90                     int length = clientSocket.Receive(buffer);
 91                     Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));
 92                 }
 93                 catch (Exception ex)
 94                 {
 95                     Console.WriteLine(ex.Message);
 96                     clientSocket.Shutdown(SocketShutdown.Both);
 97                     clientSocket.Close();
 98                     break;
 99                 }
100             }
101         }
102     }
103 }
View Code

2.客户端代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Text;
 7 using System.Threading;
 8 using System.Threading.Tasks;
 9  
10 namespace SocketUtil
11 {
12     public class SocketClient
13     {
14         private string _ip = string.Empty;
15         private int _port = 0;
16         private Socket _socket = null;
17         private byte[] buffer = new byte[1024 * 1024 * 2];
18  
19         /// <summary>
20         /// 构造函数
21         /// </summary>
22         /// <param name="ip">连接服务器的IP</param>
23         /// <param name="port">连接服务器的端口</param>
24         public SocketClient(string ip, int port)
25         {
26             this._ip = ip;
27             this._port = port;
28         }
29         public SocketClient(int port)
30         {
31             this._ip = "127.0.0.1";
32             this._port = port;
33         }
34  
35         /// <summary>
36         /// 开启服务,连接服务端
37         /// </summary>
38         public void StartClient()
39         {
40             try
41             {
42                 //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
43                 _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
44                 //2.0 创建IP对象
45                 IPAddress address = IPAddress.Parse(_ip);
46                 //3.0 创建网络端口包括ip和端口
47                 IPEndPoint endPoint = new IPEndPoint(address, _port);
48                 //4.0 建立连接
49                 _socket.Connect(endPoint);
50                 Console.WriteLine("连接服务器成功");
51                 //5.0 接收数据
52                 int length = _socket.Receive(buffer);
53                 Console.WriteLine("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer,0,length));
54                 //6.0 像服务器发送消息
55                 for (int i = 0; i < 10; i++)
56                 {
57                     Thread.Sleep(2000);
58                     string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());
59                     _socket.Send(Encoding.UTF8.GetBytes(sendMessage));
60                     Console.WriteLine("像服务发送的消息:{0}", sendMessage);
61                 }
62             }
63             catch (Exception ex)
64             {
65                 _socket.Shutdown(SocketShutdown.Both);
66                 _socket.Close();
67                 Console.WriteLine(ex.Message);
68             }
69             Console.WriteLine("发送消息结束");
70             Console.ReadKey();
71         }
72     }
73 }
View Code

3.分别开启客户端和服务端

 1 using SocketUtil;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7  
 8 namespace SocketClientApp
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             SocketClient client = new SocketClient(8888);
15             client.StartClient();
16             Console.ReadKey();
17         }
18     }
19 }
View Code
 1 using SocketUtil;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7  
 8 namespace SocketServerApp
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             SocketServer server = new SocketServer(8888);
15             server.StartListen();
16             Console.ReadKey();
17         }
18     }
19 }
View Code

 转 https://blog.csdn.net/qq_33022911/article/details/82432778

原文地址:https://www.cnblogs.com/anyihen/p/12832145.html