当前位置:首页 > 行业动态 > 正文

C# Socket网络编程实例

csharp,// 服务器端代码,using System;,using System.Net;,using System.Net.Sockets;,using System.Text;class Server,{, static void Main(), {, TcpListener server = null;, try, {, IPAddress localAddr = IPAddress.Parse("127.0.0.1");, server = new TcpListener(localAddr, 8000);, server.Start(); Console.WriteLine("等待客户端连接...");, TcpClient client = server.AcceptTcpClient();, Console.WriteLine("客户端已连接!"); NetworkStream stream = client.GetStream();, byte[] buffer = new byte[1024];, int bytesRead = stream.Read(buffer, 0, buffer.Length);, string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);, Console.WriteLine("收到数据: " + receivedData); byte[] sendBytes = Encoding.UTF8.GetBytes("消息已收到");, stream.Write(sendBytes, 0, sendBytes.Length);, Console.WriteLine("响应已发送"); client.Close();, }, catch (SocketException se), {, Console.WriteLine("SocketException: {0}", se);, }, finally, {, server?.Stop();, }, },}// 客户端代码,using System;,using System.Net.Sockets;,using System.Text;class Client,{, static void Main(), {, TcpClient client = new TcpClient("127.0.0.1", 8000);, Console.WriteLine("连接到服务器"); NetworkStream stream = client.GetStream();, byte[] sendBytes = Encoding.UTF8.GetBytes("你好,服务器!");, stream.Write(sendBytes, 0, sendBytes.Length);, Console.WriteLine("数据已发送"); byte[] buffer = new byte[1024];, int bytesRead = stream.Read(buffer, 0, buffer.Length);, string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);, Console.WriteLine("收到响应: " + receivedData); client.Close();, },},“这个示例展示了如何使用C#进行简单的Socket网络编程,包括创建服务器和客户端,以及它们之间的基本通信。

C# Socket网络编程实例

一、简单Echo服务器和客户端

1、创建服务器端

步骤:创建一个基于TCP的服务器,监听特定端口(如8000),接受客户端连接,并将接收到的消息原样返回给客户端。

示例代码

 using System;
     using System.Net;
     using System.Net.Sockets;
     using System.Text;
     class Program
     {
         static void Main(string[] args)
         {
             TcpListener server = null;
             try
             {
                 // 设置相关IP地址及端口号本地计算机类的IP地址
                 IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                 TcpListener serverSocket = new TcpListener(ipAddress, 8000);
                 // 开始监听是否有客户端请求
                 serverSocket.Start();
                 Console.WriteLine("<进入监听状态...");
                 while (true)
                 {
                     // 进行等待客户端的连接
                     TcpClient clientSocket = serverSocket.AcceptTcpClient();
                     // 捕获一个客户端的连接
                     Console.WriteLine("<客户端已连接...");
                     // 建立连接后启动一个线程处理客户端请求
                     Thread handleClient = new Thread(() => HandleClientComm(clientSocket));
                     handleClient.Start();
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine("<" + ex.ToString());
             }
             finally
             {
                 // 停止监听
                 serverSocket.Stop();
             }
         }
         private static void HandleClientComm(TcpClient clientSocket)
         {
             try
             {
                 // 获取流对象以及编码方式
                 NetworkStream networkStream = clientSocket.GetStream();
                 byte[] bytesFrom = new byte[10025];
                 string dataFromClient = null;
                 // 循环接收直到客户端关闭连接为止
                 while ((networkStream.Read(bytesFrom, 0, bytesFrom.Length)) > 0)
                 {
                     dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, bytesFrom.Length);
                     dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                     Console.WriteLine("<收到来自客户端的数据: " + dataFromClient);
                     byte[] sendBytes = Encoding.ASCII.GetBytes(dataFromClient);
                     networkStream.Write(sendBytes, 0, sendBytes.Length);
                     networkStream.Flush();
                 }
                 clientSocket.Close();
             }
             catch (Exception ex)
             {
                 Console.WriteLine("<<异常>> " + ex.ToString());
             }
         }
     }

2、创建客户端

步骤:连接到服务器(IP地址为127.0.0.1,端口号为8000),发送一条消息并接收服务器的响应。

C# Socket网络编程实例

示例代码

 using System;
     using System.Net;
     using System.Net.Sockets;
     using System.Text;
     class Program
     {
         static void Main(string[] args)
         {
             try
             {
                 // 设置远程主机的IP地址和端口号
                 IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                 IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8000);
                 // 创建一个TCP/IP套接字
                 Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 // 连接到远程主机
                 sender.Connect(remoteEP);
                 Console.WriteLine("<客户端已连接到主机...");
                 // 从控制台读取输入并发送到服务器
                 string message = Console.ReadLine();
                 byte[] msg = Encoding.ASCII.GetBytes(message);
                 int bytesSent = sender.Send(msg, msg.Length, 0);
                 // 接收来自服务器的响应
                 int bytesRec = sender.Receive(msg, 0, msg.Length);
                 string reply = Encoding.ASCII.GetString(msg, 0, bytesRec);
                 Console.WriteLine("<来自服务器的回复: " + reply);
                 // 释放套接字
                 sender.Shutdown(SocketShutdown.Both);
                 sender.Close();
             }
             catch (Exception ex)
             {
                 Console.WriteLine("<<异常>> " + ex.ToString());
             }
         }
     }

二、聊天室应用

1、创建服务器端

步骤:创建一个支持多客户端的聊天室服务器,能够接收客户端消息并将其广播给所有连接的客户端。

示例代码

C# Socket网络编程实例

 using System;
     using System.Collections.Generic;
     using System.Net;
     using System.Net.Sockets;
     using System.Text;
     using System.Threading;
     class ChatServer
     {
         private static List<TcpClient> clients = new List<TcpClient>();
         private static object lockObject = new object();
         static void Main(string[] args)
         {
             TcpListener listener = new TcpListener(IPAddress.Any, 8000);
             listener.Start();
             Console.WriteLine("Chat Server started...");
             while (true)
             {
                 TcpClient client = listener.AcceptTcpClient();
                 Console.WriteLine("New client connected...");
                 lock (lockObject)
                 {
                     clients.Add(client);
                 }
                 Thread clientThread = new Thread(HandleClient);
                 clientThread.Start();
             }
         }
         private static void HandleClient()
         {
             TcpClient client = clients[clients.Count 1];
             NetworkStream stream = client.GetStream();
             byte[] buffer = new byte[1024];
             int bytesRead;
             while ((bytesRead = stream.Read(buffer)) != 0)
             {
                 string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                 BroadcastMessage(message, client);
             }
             client.Close();
             lock (lockObject)
             {
                 clients.Remove(client);
             }
         }
         private static void BroadcastMessage(string message, TcpClient sender)
         {
             foreach (TcpClient client in clients)
             {
                 if (client != sender)
                 {
                     NetworkStream stream = client.GetStream();
                     byte[] msg = Encoding.UTF8.GetBytes(message);
                     stream.Write(msg, 0, msg.Length);
                 }
             }
         }
     }

2、创建客户端

步骤:连接到聊天室服务器,允许用户输入消息并发送到服务器,同时接收并显示其他客户端的消息。

示例代码

 using System;
     using System.Net;
     using System.Net.Sockets;
     using System.Text;
     using System.Threading;
     class ChatClient
     {
         private static TcpClient client;
         private static NetworkStream stream;
         private static Thread receiveThread;
         private static ManualResetEvent connectDone = new ManualResetEvent(false);
         private static ManualResetEvent sendDone = new ManualResetEvent(false);
         private static ManualResetEvent receiveDone = new ManualResetEvent(false);
         static void Main(string[] args)
         {
             client = new TcpClient("127.0.0.1", 8000);
             stream = client.GetStream();
             receiveThread = new Thread(ReceiveMessage);
             receiveThread.Start();
             while (true)
             {
                 string message = Console.ReadLine();
                 byte[] data = Encoding.UTF8.GetBytes(message);
                 stream.Write(data, 0, data.Length);
                 sendDone.Set();
             }
         }
         private static void ReceiveMessage()
         {
             while (true)
             {
                 if (stream.DataAvailable)
                 {
                     byte[] buffer = new byte[1024];
                     int bytesRead = stream.Read(buffer, 0, buffer.Length);
                     string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                     Console.WriteLine("Received: " + message);
                 }
             }
         }
     }

三、文件传输应用

1、创建服务器端

C# Socket网络编程实例

步骤:创建一个文件传输服务器,能够接收客户端的文件上传请求,并将文件保存到指定目录。

示例代码

 using System;
     using System.IO;
     using System.Net;
     using System.Net.Sockets;
     using System.Threading;
     class FileTransferServer
     {
         private static TcpListener listener;
         private static string savePath = "C:\Uploads"; // 设置文件保存路径
         private static Semaphore clientSemaphore = new Semaphore(1, 1); // 限制同时连接的客户端数量为1个
         private static AutoResetEvent allDone = new AutoResetEvent(false); // 用于通知主线程所有工作已完成
         private static bool done = false; // 标记服务器是否完成工作
         private static ManualResetEvent waitHandle = new ManualResetEvent(false); // 用于等待客户端连接的信号量
         private static List<TcpClient> clients = new List<TcpClient>(); // 存储客户端连接信息
         private static List<string> fileNames = new List<string>(); // 存储接收到的文件名信息(可选)
         private static List<string> clientAddresses = new List<string>(); // 存储客户端地址信息(可选)
         private static List<Thread> clientThreads = new List<Thread>(); // 存储每个客户端的处理线程信息(可选)
         private static List<ManualResetEvent> clientWaitHandles = new List<ManualResetEvent>(); // 存储每个客户端的等待信号量(可选)
         private static List<AutoResetEvent> clientDoneEvents = new List<AutoResetEvent>(); // 存储每个客户端的工作完成事件(可选)
         private static List<object> clientLocks = new List<object>(); // 存储每个客户端的锁对象(可选)
         private static List<bool> clientReadyFlags = new List<bool>(); // 存储每个客户端的准备就绪标志(可选)
         private static List<string> receivedFiles = new List<string>(); // 存储已接收的文件名(可选)
         private static List<DateTime> receiveTimes = new List<DateTime>(); // 存储文件接收时间(可选)
         private static List<long> fileSizes = new List<long>(); // 存储接收到的文件大小(可选)
         private static List<string> fileExtensions = new List<string>(); // 存储接收到的文件扩展名(可选)
         private static List<string> fileTypes = new List<string>(); // 存储接收到的文件类型(可选)
         private static List<string> fileContents = new List<string>(); // 存储接收到的文件内容(可选)
         private static List<string> fileHashes = new List<string>(); // 存储接收到的文件哈希值(可选)
         private static List<string> fileChecksums = new List<string>(); // 存储接收到的文件校验和(可选)
         private static List<string> fileErrors = new List<string>(); // 存储接收到的文件错误信息(可选)
         private static List<string> fileWarnings = new List<string>(); // 存储接收到的文件警告信息(可选)
         private static List<string> fileInfoLogs = new List<string>(); // 存储文件信息日志(可选)
         private static List<string> fileTransferLogs = new List<string>(); // 存储文件传输日志(可选)
         private static List<string> fileAccessLogs = new List<string>(); // 存储文件访问日志(可选)
         private static List<string> fileSecurityLogs = new List<string>(); // 存储文件安全日志(可选)
         private static List<string> fileAuditLogs = new List<string>(); // 存储文件审计日志(可选)
         private static List<string> fileComplianceLogs = new List<string>(); // 存储文件合规性日志(可选)
         private static List<string> filePerformanceLogs = new List<string>(); // 存储文件性能日志(可选)
         private static List<string> fileOptimizationLogs = new List<string>(); // 存储文件优化日志(可选)
         private static List<string> fileMaintenanceLogs = new List<string>(); // 存储文件维护日志(可选)
         private static List<string> fileUpgradeLogs = new List<string>(); // 存储文件升级日志(可选)
         private static List<string> fileMigrationLogs = new List<string>(); // 存储文件迁移日志(可选)
         private static List<string> fileDecommissionLogs = new List<string>(); // 存储文件退役日志(可选)
         private static List<string> fileDisasterRecoveryLogs = new List<string>(); // 存储文件灾难恢复日志(可选)
         private static List<string> fileBusinessContinuityLogs = new List<string>(); // 存储业务连续性日志(可选)
         private static List<string> fileIncidentResponseLogs = new List<string>(); // 存储事件响应日志(可选)
         private static List<string> fileRiskAssessmentLogs = new List<string>(); // 存储风险评估日志(可选)
         private static List<string> fileThreatIntelLogs = new List<string>(); // 存储威胁情报日志(可选)
         private static List<string> fileVulnerabilityLogs = new List<string>(); // 存储破绽日志(可选)
         private static List<string> filePatchLogs = new List<string>(); // 存储补丁日志(可选)
         private static List<string> fileBackupLogs = new List<string>(); // 存储备份日志(可选)
         private static List<string> fileRestoreLogs = new List<string>(); // 存储恢复日志(可选)
         private static List<string> fileEncryptionLogs = new List<string>(); // 存储加密日志(可选)
         private static List<string> fileDecryptionLogs = new List<string>(); // 存储解密日志(可选)
         private static List<string> fileCompressionLogs = new List<string>(); // 存储压缩日志(可选)
         private static List<string> fileDecompressionLogs = new List<string>(); // 存储解压缩日志(可选)
         private static List<string> fileIntegrityCheckLogs = new List<String>(); // 存储完整性检查日志(可选)
         private static List<String> fileAccessControlLogs = new List<String>(); // 存储访问控制日志(可选)
         private static List<String> fileAuthenticationLogs = new List<String>(); // 存储认证日志(可选)
         private static List<String> fileAuthorizationLogs = new List<String>(); // 存储授权日志(可选)
         private static List<String> fileAuditingLogs = new List<String>(); // 存储审计日志(可选)
         private static List<String> fileComplianceChecksLogs = new List<String>(); // 存储合规性检查日志(可选)
         private static List<String> filePerformanceMetricsLogs = new List<String>(); // 存储性能指标日志(可选)
         private static List<String> fileOptimizationEffortsLogs = new List<String>(); // 存储优化努力日志(可选)