导图社区 Socket知识导图
网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个Socket。本图详细的梳理了相关知识内容,收藏下图学习吧!
编辑于2021-09-05 09:54:10介绍归纳 C Sharp 语音的基础重点知识。包括语言基础、字面常量、程序集、不安全代码、基础类、枚举、数组、泛型、字符串、正则表达式、委托与事件、文件、异常、多线程、异步、反射、网络、绘图、WinForm、Windows、跨平台调用等内容。思维导图示例中,有示例代码,方便学习与练习。
这份思维导图归纳了一些HTML基本的元素标签、布局、表单,以及 HTML5 API 如 WebSockets、Fetch API 等内容。CSS 主要是归纳了选择器。JavaScript 主要是包含了函数与箭头函数、this 关键字、Promise 异步对象。此外还有AJAX、jQuery 与 jQuery AJAX、JSONP 等内容。导图中的注释有很多相关的详细说明与示例代码,其中后端的测试代码是用的 PHP。希望能帮到大家!
WPF开发相关的笔记。WPF基本概念、XAML基本语法、控件与布局、Binding、依赖属性与附加属性、路由事件与附加事件、命令、资源、模板与样式、2D绘图与动画、3D绘图等内容。导图中的注释还有很多相关的详细说明与示例代码,希望能帮到大家!
社区模板帮助中心,点此进入>>
介绍归纳 C Sharp 语音的基础重点知识。包括语言基础、字面常量、程序集、不安全代码、基础类、枚举、数组、泛型、字符串、正则表达式、委托与事件、文件、异常、多线程、异步、反射、网络、绘图、WinForm、Windows、跨平台调用等内容。思维导图示例中,有示例代码,方便学习与练习。
这份思维导图归纳了一些HTML基本的元素标签、布局、表单,以及 HTML5 API 如 WebSockets、Fetch API 等内容。CSS 主要是归纳了选择器。JavaScript 主要是包含了函数与箭头函数、this 关键字、Promise 异步对象。此外还有AJAX、jQuery 与 jQuery AJAX、JSONP 等内容。导图中的注释有很多相关的详细说明与示例代码,其中后端的测试代码是用的 PHP。希望能帮到大家!
WPF开发相关的笔记。WPF基本概念、XAML基本语法、控件与布局、Binding、依赖属性与附加属性、路由事件与附加事件、命令、资源、模板与样式、2D绘图与动画、3D绘图等内容。导图中的注释还有很多相关的详细说明与示例代码,希望能帮到大家!
Socket
C语言
Windows
C#
Windows
TCP协议
建立连接三次握手

(1)客户端发送同步包SYN(seq=x)到服务器,并进入SYN_SEND状态,等待服务器确认;
(2)服务器收到SYN包,必须确认客户端的SYN(ACK=x+1),同时自己也发送一个SYN包(seq=y),即SYN+ACK包,此时服务器进入SYN_RECV状态;
(3)客户端收到服务器的SYN+ACK包,向服务器发送确认包ACK(ACK=y+1),此包发送完毕,客户端和服务器进入ESTABLISHED状态,完成三次握手。
应用
例
封装的Socket方式
客户端
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace Client { class Program { static void Main(string[] args) { TcpClient client = null; try { Console.WriteLine("连接服务器..."); client = new TcpClient("127.0.0.1", 13000); //初始化 TcpClient 类的新实例并连接到指定主机上的指定端口 if (client.Connected) { Console.WriteLine("已连接!"); using (NetworkStream stream = client.GetStream()) //获取用于发送和接收数据的 NetworkStream { while (true) { Console.Write("输入>"); string sendMsg = Console.ReadLine(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); stream.Write(sendData, 0, sendData.Length); //数据写入流 Console.WriteLine($"发:{sendMsg}"); List<byte> readData = new List<byte>(); byte[] readBuffer = new byte[256]; do { int count = stream.Read(readBuffer, 0, readBuffer.Length); //从流读数据 if (count < readBuffer.Length) { byte[] newBuffer = new byte[count]; Buffer.BlockCopy(readBuffer, 0, newBuffer, 0, count); readBuffer = newBuffer; } readData.AddRange(readBuffer); } while (stream.DataAvailable); //流上是否有可用的数据 string readMsg = Encoding.UTF8.GetString(readData.ToArray()); Console.WriteLine($"收:{readMsg}"); if (sendMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } } } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } finally { if (null != client) { client.Close(); //释放此 TcpClient 实例,并请求关闭基础 TCP 连接 } } Console.WriteLine("按任意键退出..."); Console.Read(); } } }
服务器端
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; namespace Server { class Program { static void Main(string[] args) { TcpListener server = null; try { server = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000); //初始化 TcpListener 类的新实例,该类在指定的本地 IP 地址和端口号上侦听是否有传入的连接尝试 server.Start(); //开始侦听传入的连接请求 Timer timer = new Timer(CheckConnection, server, 0, 1000); while (true) { Thread.Sleep(10000); } } catch (Exception ex) { Console.WriteLine($"侦听器异常:{ex.Message}"); } finally { if (null != server) { server.Stop(); //关闭侦听器 } } Console.WriteLine("按任意键退出..."); Console.Read(); } static void CheckConnection(object obj) { try { TcpListener server = obj as TcpListener; if (server.Pending()) //是否有挂起的连接请求 { Console.WriteLine("检测到客户端连接..."); ThreadPool.QueueUserWorkItem(ConnectionHandle, server); } } catch (Exception ex) { Console.WriteLine($"检测客户端连接过程异常:{ex.Message}"); } } static void ConnectionHandle(object obj) { TcpListener server = obj as TcpListener; TcpClient client = null; try { Console.WriteLine($"接受客户端连接... 处理线程:{Thread.CurrentThread.ManagedThreadId}"); client = server.AcceptTcpClient(); //接受挂起的连接请求,返回用于发送和接收数据的 TcpClient。(该方法为阻塞方法) if (client.Connected) { Console.WriteLine("已连接!"); using (NetworkStream stream = client.GetStream()) //获取用于发送和接收数据的 NetworkStream { while (true) { List<byte> readData = new List<byte>(); byte[] readBuffer = new byte[256]; do { int count = stream.Read(readBuffer, 0, readBuffer.Length); //从流读数据 if (count < readBuffer.Length) { byte[] newBuffer = new byte[count]; Buffer.BlockCopy(readBuffer, 0, newBuffer, 0, count); readBuffer = newBuffer; } readData.AddRange(readBuffer); } while (stream.DataAvailable); //流上是否有可用的数据 string readMsg = Encoding.UTF8.GetString(readData.ToArray()); Console.WriteLine($"收:{readMsg} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); string sendMsg = readMsg.ToUpper(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); stream.Write(sendData, 0, sendData.Length); //数据写入流 Console.WriteLine($"发:{sendMsg} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); if (readMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } } } catch (Exception ex) { Console.WriteLine($"连接异常:{ex.Message} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); } finally { if (null != client) { client.Close(); //释放此 TcpClient 实例,并请求关闭基础 TCP 连接 } Console.WriteLine($"断开客户端连接。 处理线程:{Thread.CurrentThread.ManagedThreadId}"); } } } }
Socket方式
客户端
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace Client { class Program { static void Main(string[] args) { Socket socket = null; try { Console.WriteLine("连接服务器..."); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //初始化 Socket 类的新实例 socket.Connect("127.0.0.1", 13000); //建立与远程主机的连接 if (socket.Connected) { Console.WriteLine("已连接!"); while (true) { Console.Write("输入>"); string sendMsg = Console.ReadLine(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); socket.Send(sendData); //发送数据 Console.WriteLine($"发:{sendMsg}"); List<byte> readData = new List<byte>(); byte[] readBuffer = new byte[256]; do { int count = socket.Receive(readBuffer); //接收数据 if (count < readBuffer.Length) { byte[] newBuffer = new byte[count]; Buffer.BlockCopy(readBuffer, 0, newBuffer, 0, count); readBuffer = newBuffer; } readData.AddRange(readBuffer); } while (socket.Available > 0); //是否还有可用的数据 string readMsg = Encoding.UTF8.GetString(readData.ToArray()); Console.WriteLine($"收:{readMsg}"); if (sendMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } finally { if (null != socket) { socket.Close(); //关闭 Socket 连接并释放所有关联的资源 } } Console.WriteLine("按任意键退出..."); Console.Read(); } } }
服务器端
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; namespace Server { class Program { static void Main(string[] args) { Socket socket = null; try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //初始化 Socket 类的新实例 socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000)); //使 Socket 与一个本地终结点相关联 socket.Listen(int.MaxValue); //将 Socket 置于侦听状态 Timer timer = new Timer(CheckConnection, socket, 0, 1000); while (true) { Thread.Sleep(10000); } } catch (Exception ex) { Console.WriteLine($"侦听器异常:{ex.Message}"); } finally { if (null != socket) { socket.Close(); //关闭 Socket 连接并释放所有关联的资源 } } Console.WriteLine("按任意键退出..."); Console.Read(); } static void CheckConnection(object obj) { try { Socket socket = obj as Socket; if (socket.Poll(0, SelectMode.SelectRead)) //是否有挂起的连接请求 { Console.WriteLine("检测到客户端连接..."); ThreadPool.QueueUserWorkItem(ConnectionHandle, socket); } } catch (Exception ex) { Console.WriteLine($"检测客户端连接过程异常:{ex.Message}"); } } static void ConnectionHandle(object obj) { Socket socket = obj as Socket; Socket client = null; try { Console.WriteLine($"接受客户端连接... 处理线程:{Thread.CurrentThread.ManagedThreadId}"); client = socket.Accept(); //以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket。(该方法为阻塞方法) if (client.Connected) { Console.WriteLine("已连接!"); while (true) { List<byte> readData = new List<byte>(); byte[] readBuffer = new byte[256]; do { int count = client.Receive(readBuffer); //接收数据 if (count < readBuffer.Length) { byte[] newBuffer = new byte[count]; Buffer.BlockCopy(readBuffer, 0, newBuffer, 0, count); readBuffer = newBuffer; } readData.AddRange(readBuffer); } while (client.Available > 0); //是否还有可用的数据 string readMsg = Encoding.UTF8.GetString(readData.ToArray()); Console.WriteLine($"收:{readMsg} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); string sendMsg = readMsg.ToUpper(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); client.Send(sendData); //发送数据 Console.WriteLine($"发:{sendMsg} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); if (readMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } client.Shutdown(SocketShutdown.Both); //禁用 Socket 上的发送和接收 } catch (Exception ex) { Console.WriteLine($"连接异常:{ex.Message} 处理线程:{Thread.CurrentThread.ManagedThreadId}"); } finally { if (null != client) { client.Close(); //关闭 Socket 连接并释放所有关联的资源 } Console.WriteLine($"断开客户端连接。 处理线程:{Thread.CurrentThread.ManagedThreadId}"); } } } }
UDP协议
应用
例
封装的Socket方式
终端1
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace Terminal { class Program { static void Main(string[] args) { IPEndPoint localHost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000); IPEndPoint remoteHost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13001); UdpClient terminal = null; try { Console.WriteLine("初始化..."); terminal = new UdpClient(localHost); //初始化 UdpClient 类的新实例,并将其绑定到指定的本地终结点 Console.WriteLine("完成!"); while (true) { Console.Write("输入>"); string sendMsg = Console.ReadLine(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); terminal.Send(sendData, sendData.Length, remoteHost); //将 UDP 数据报发送到远程主机 Console.WriteLine($"发:{sendMsg}"); byte[] readBuffer = terminal.Receive(ref remoteHost); //接收远程主机发送的 UDP 数据报 string readMsg = Encoding.UTF8.GetString(readBuffer); Console.WriteLine($"收:{readMsg}"); if (sendMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } finally { if (null != terminal) { terminal.Close(); //关闭 UDP 连接 } } Console.WriteLine("按任意键退出..."); Console.Read(); } } }
终端2
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace Terminal { class Program { static void Main(string[] args) { IPEndPoint localHost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13001); IPEndPoint remoteHost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000); UdpClient terminal = null; try { Console.WriteLine("初始化..."); terminal = new UdpClient(localHost); //初始化 UdpClient 类的新实例,并将其绑定到指定的本地终结点 Console.WriteLine("完成!"); while (true) { byte[] readBuffer = terminal.Receive(ref remoteHost); //接收远程主机发送的 UDP 数据报 string readMsg = Encoding.UTF8.GetString(readBuffer); Console.WriteLine($"收:{readMsg}"); string sendMsg = readMsg.ToUpper(); byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); terminal.Send(sendData, sendData.Length, remoteHost); //将 UDP 数据报发送到远程主机 Console.WriteLine($"发:{sendMsg}"); if (readMsg.Equals("exit", StringComparison.OrdinalIgnoreCase)) { break; } } } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } finally { if (null != terminal) { terminal.Close(); //关闭 UDP 连接 } } Console.WriteLine("按任意键退出..."); Console.Read(); } } }