C# 网络通信的基本框架 源代码
一、基于 Socket 的 TCP 通信
服务器端
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace SimpleIMSocketTcpServer { class Program { static void Main(string[] args) { Socket localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 888); localSocket.Bind(iep); localSocket.Listen(1); Socket clientSocket = localSocket.Accept(); Console.WriteLine("localSocket: {0}:{1} .", ((IPEndPoint)localSocket.LocalEndPoint).Address, ((IPEndPoint)localSocket.LocalEndPoint).Port); //Console.WriteLine("localSocket: {0}:{1} <-> {2}:{3} .", ((IPEndPoint)localSocket.LocalEndPoint).Address, ((IPEndPoint)localSocket.LocalEndPoint).Port, ((IPEndPoint)localSocket.RemoteEndPoint).Address, ((IPEndPoint)localSocket.RemoteEndPoint).Port); Console.WriteLine("clientSocket: {0}:{1} <-> {2}:{3} .", ((IPEndPoint)clientSocket.LocalEndPoint).Address, ((IPEndPoint)clientSocket.LocalEndPoint).Port, ((IPEndPoint)clientSocket.RemoteEndPoint).Address, ((IPEndPoint)clientSocket.RemoteEndPoint).Port); clientSocket.Send(Encoding.Default.GetBytes("服务器端: 欢迎加入")); byte[] myresult = new byte[1024]; int length = clientSocket.Receive(myresult); string szData = Encoding.Default.GetString(myresult, 0, length); //myresult[length] = 0; Console.WriteLine("来自 {0} : {1}", clientSocket.RemoteEndPoint, szData); //localSocket.Shutdown(SocketShutdown.Both); localSocket.Close(); } } }
客户端
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace SimpleIMSocketTcpClient { class Program { static void Main(string[] args) { IPAddress remoteHost = IPAddress.Parse("127.0.0.1"); IPEndPoint iep = new IPEndPoint(remoteHost, 888); Socket localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localSocket.Connect(iep); string sendMessage = "客户端: 你好"; localSocket.Send(Encoding.Default.GetBytes(sendMessage)); byte[] result = new byte[1024]; int length = localSocket.Receive(result); Console.WriteLine("localSocket: {0} <-> {1} .", localSocket.LocalEndPoint, localSocket.RemoteEndPoint); Console.WriteLine("来自: {0} : {1}", localSocket.RemoteEndPoint, Encoding.Default.GetString(result, 0, length)); localSocket.Shutdown(SocketShutdown.Both); localSocket.Close(); } } }
二、基于 Socket 的 UDP 通信
服务器端
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace SimpleIMSocketUdpServer { class Program { static void Main(string[] args) { // 开启服务器的 888 端口,用来接收任何传送到本机的讯息。 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 888); // 建立接收的 Socket,并使用 Udp 的 Datagram 方式接收。 Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 绑定 Socket (newsock) 与 IPEndPoint (ipep),让 Socket 接收 888 端口的讯息。 newsock.Bind(ipep); Console.WriteLine("等待客户连入 . . . "); // 建立 Remote 对象以便取得封包的接收来源的 EndPoint 对象。 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); while (true) // 无穷循环,不断接收讯息并显示到屏幕上。 { byte[] data = new byte[1024]; // 设定接收缓冲区的数组变量。 int recv = newsock.ReceiveFrom(data, ref Remote); // 接收对方传来的封包。 // 将该封包以 UTF8 的格式译码为字符串,并显示到屏幕上。 string recvString = Encoding.UTF8.GetString(data, 0, recv); // 读取键盘输入 Console.WriteLine(recvString); if (recvString == "exit") break; } Console.WriteLine("断开连接"); newsock.Close(); } } }
客户端
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace SimpleIMSocketUdpClient { class Program { static void Main(string[] args) { // 连接到 args[0] 参数所指定的 Server,使用端口 888 //IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(args[0]), 888); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 888); // 建立 Socket,连接到 Internet (InterNetwork),使用 Udp 协议的 Datagram 方式 (Dgram)。 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); while (true) // 不断读取键盘输入,并传送输入讯息给服务器。 { string input = Console.ReadLine(); // 读取键盘输入 server.SendTo(Encoding.UTF8.GetBytes(input), ipep); // 将讯息以 UTF8 的方式编码后传出。 if (input == "exit") // 如果输入为 exit,则强制离开程序。 break; } Console.WriteLine("客户端停止"); // 印出 Stopping client 讯息。 server.Close(); // 关闭联机。 } } }
三、基于 TcpListener 和 TcpClient 的 TCP 通信
服务器端
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace SimpleIMTcpServer { class Program { static void Main(string[] args) { IPAddress localip = IPAddress.Any; TcpListener listener = new TcpListener(localip, 888); listener.Start(); while (true) { //等待客户端连接; TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("{0} <-> {1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint); //确定连接后,发送信息; string msg = "来自服务器端的消息. "; NetworkStream clientStream = client.GetStream(); byte[] temp = Encoding.Default.GetBytes(msg); clientStream.Write(temp, 0, temp.Length); byte[] result = new byte[1024]; int length = clientStream.Read(result, 0, 1024); string szData = Encoding.Default.GetString(result, 0, length); Console.WriteLine("来自 {0} : {1}", client.Client.RemoteEndPoint, szData); //发送完毕后关闭连接; clientStream.Close(); client.Close(); } } } }
客户端
using System; using System.Text; using System.Net.Sockets; namespace SimpleIMTcpClient { class Program { static void Main(string[] args) { TcpClient client = new TcpClient(); try { client.Connect("127.0.0.1", 888); } catch (Exception ex) { Console.WriteLine(ex.Message); } //读取信息 NetworkStream serverStream = client.GetStream(); string sendMessage = "客户端: 你好"; serverStream.Write(Encoding.Default.GetBytes(sendMessage), 0, sendMessage.Length); byte[] buffer = new byte[1024]; int bytesread = serverStream.Read(buffer, 0, 1024); string message = Encoding.Default.GetString(buffer, 0, bytesread); Console.WriteLine("{0} <-> {1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint); Console.WriteLine(message); //关闭连接 serverStream.Close(); client.Close(); } } }
四、基于 UdpClient 的 UDP 通信
服务器端
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SimpleIMUdpServer { class Program { static void Main(string[] args) { //创建UDPClient对象 UdpClient client = new UdpClient(888); //接受发送主机的IP地址信息 IPEndPoint remoteclient = new IPEndPoint(IPAddress.Any, 0); while (true) { //Receive方法包含一个IPEndPoint,携带远程发送主机的IP地址信息 byte[] recv = client.Receive(ref remoteclient); string data = Encoding.Default.GetString(recv); Console.WriteLine("来源 : {0}", remoteclient.ToString()); Console.WriteLine("内容 : {0}", data); if (data == "exit") break; } Console.WriteLine("连接已断开."); client.Close(); } } }
客户端
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SimpleIMUdpClient { class Program { static void Main(string[] args) { //UDPClient对象创建,发送数据 UdpClient client1 = new UdpClient(889); IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 888); while (true) { string sendMsg = Console.ReadLine(); // 读取键盘输入 client1.Send(Encoding.Default.GetBytes(sendMsg), sendMsg.Length, ipe); if (sendMsg == "exit") // 如果输入为 exit,则强制离开程序。 break; } Console.WriteLine("客户端停止"); // 印出 Stopping client 讯息。 client1.Close(); } } }
执行程序下载
浙公网安备 33010602011771号