C# WPF 基于TCP协议,通过Socket类实现网络通信(服务端)(一个服务端对多个客户端进行通信)

这篇博客介绍了如何在C# WPF应用中使用Socket类建立基于TCP协议的服务端,详细讲解了如何实现一个服务端与多个客户端之间的网络通信,并提供了类库和调用方法的简单教程。
摘要由CSDN通过智能技术生成

直接Ctrl+c再Ctrl+v就能直接用了,纯小白教程。

类库+调用方法

  • 类库
    class CsSocketService
    {
   
        /// <summary>
        /// 作者:WangJunLiang || Wechat:Joronwongx
        /// </summary>

        public delegate void ReceClientData(string strRp, byte[] Buf, int nBufLenght);
        public event ReceClientData SendReceEnvent;

        public struct SocketServiceIP
        {
   
            public string strIpAddress;
            public int nPort;
            public int nMaxClientConnectCnt;
        };

        #region 线程管理

        //管理者线程
        private Socket m_ServiceMaster = null;
        private BackgroundWorker m_ClientAdministrator_BackgroundWorker = null;

        //用户线程
        public struct SocketServiceChild
        {
   
            public Socket socket;
            public BackgroundWorker backgroundWorker;
        };
        public Dictionary<string, SocketServiceChild> m_LSocketServiceChild = new Dictionary<string, SocketServiceChild>(); //是二叉树式的存储结构,不支持用索引来取值,想取只能遍历

        #endregion

        #region 监听服务
        //创建多个子服务器的消息接收线程
        private void CreateClientReceClick(object sender, DoWorkEventArgs e)
        {
   
            while (!m_ClientAdministrator_BackgroundWorker.CancellationPending)
            {
   
                Socket socketItem = m_ServiceMaster.Accept();                                   //阻塞监听
                if (m_ClientAdministrator_BackgroundWorker.CancellationPending)                   //支线程是否被挂起取消
                    break;
                if (socketItem != null)
                {
   
                    BackgroundWorker ServiceChild_BackgroundWorker = new BackgroundWorker();
                    ServiceChild_BackgroundWorker.DoWork += ReceClientDataClick;                //持续监听绑定的客户端
                    ServiceChild_BackgroundWorker.WorkerSupportsCancellation 
以下是一个简单的 WPF 客户端服务端 TCP 通信的示例代码: 服务端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Server { class Program { static void Main(string[] args) { TcpListener server = null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also use server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a ASCII string. data = Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } } ``` 客户端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Client { class Program { static void Main(string[] args) { string server = "127.0.0.1"; int port = 13000; try { TcpClient client = new TcpClient(server, port); // Translate the passed message into ASCII and store it as a Byte array. string message = "Hello, server!"; byte[] data = Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new byte[256]; // String to store the response ASCII representation. string responseData = string.Empty; // Read the first batch of the TcpServer response bytes. int bytes = stream.Read(data, 0, data.Length); responseData = Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } } ``` 这里使用了 .NET Framework 自带的 TCP 相关服务端使用 `TcpListener` 监听客户端连接客户端使用 `TcpClient` 连接服务器,使用 `NetworkStream` 进行数据通信。注意修改 IP 地址和端口号以适应您的需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值