本文最后更新于 2024-07-31,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。

Socket服务端

代码示例

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SocketDemo
{
    public class SocketServer
    {
        //声明一个Socket对象
        private Socket socketSever;

        //创建字典集合,键是ClientIp,值是SocketClient
        private Dictionary<string, Socket> CurrentClientlist = new Dictionary<string, Socket>();

        /// <summary>
        /// 开启服务
        /// </summary>
        public void StartService(string ip,int port)
        {
            // 调用socket()函数创建一个用于通信的套接字
            socketSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用bind()函数来实现。
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);

            try
            {
                socketSever.Bind(ipe);
            }
            catch (Exception ex)
            {
                //写入日志
                Console.WriteLine("服务器开启失败:" + ex.Message);
                return;
            }

            // 调用listen()函数使套接字成为一个监听套接字。
            socketSever.Listen(10);

            //创建一个监听的线程
            var listenThread = new Thread(new ThreadStart(CheckListening));
            listenThread.IsBackground = true;
            listenThread.Start();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="ip">客户端ip</param>
        /// <param name="msg">消息</param>
        public void SendMsg(string ip, string msg)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            if (CurrentClientlist.ContainsKey(ip))
            {
                Socket client = CurrentClientlist[ip];
                client.Send(buffer);
            }
        }

        /// <summary>
        /// 检查监听的线程方法体
        /// </summary>
        private void CheckListening()
        {
            while (true)
            {
                // 调用accept()函数来接受客户端的连接,这时就可以和客户端通信了。
                Socket socketClient = socketSever.Accept();

                string client = socketClient.RemoteEndPoint.ToString();

                Console.WriteLine(client + "上线了");

                CurrentClientlist.Add(client, socketClient);

                Thread receiveMsgTread = new Thread(new ParameterizedThreadStart(ReceiveMessage));
                receiveMsgTread.Start(socketClient);
            }
        }

        /// <summary>
        /// 接收客户端数据的方法
        /// </summary>
        /// <param name="socketClient"></param>
        private void ReceiveMessage(object socketClient)
        {
            Socket socket = (Socket)socketClient;
            while (true)
            {
                // 创建一个缓冲区
                byte[] buffer = new byte[1024 * 1024 * 10];

                int length = -1;

                string client = socket.RemoteEndPoint.ToString();

                // 处理客户端的连接请求。
                try
                {
                    length = socket.Receive(buffer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error:" + ex.Message);
                    Console.WriteLine(client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }

                if (length > 0)
                {
                    string msg = Encoding.UTF8.GetString(buffer, 0, length);
                    Console.WriteLine(client + ":" + msg);
                }
                else
                {
                    Console.WriteLine(client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }
            }
        }

    }
}

使用

using System;
using System.Collections.Generic;
using System.Text;

namespace SocketDemo
{
    public class MainServer
    {
        SocketServer server;
        public MainServer()
        {
            server = new SocketServer();
            // 开启服务并监听客户端发送的数据
            server.StartService("127.0.0.1",9997);
            // 向指定客户端发送消息
            server.Send("127.0.0.1","Hello");
        }
    }
}

Socket客户端

代码示例

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SocketDemo
{
    public class SocketClient
    {
        private Socket socketClient;

        /// <summary>
        /// 建立连接
        /// </summary>
        /// <param name="ip"> IP地址 </param>
        /// <param name="port"> 端口 </param>
        public void Connect(string ip, int port)
        {
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);
            try
            {
                socketClient.Connect(ipe);
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接服务器失败:" + ex.Message);
                return;
            }

            // 创建一个监听线程
            var checkReceiveMsgThread = new Thread(new ThreadStart(CheckReceiveMsg));
            checkReceiveMsgThread.IsBackground = true;
            checkReceiveMsgThread.Start();

            Console.WriteLine("成功连接至服务器");
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {
            if (socketClient != null)
            {
                socketClient.Close();
                Console.WriteLine("与服务器断开连接");
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        public void SendMsg(string msg)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            if (socketClient != null)
            {
                socketClient.Send(buffer);
                Console.WriteLine("发送内容:" + msg);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        public void CheckReceiveMsg()
        {
            while (true)
            {
                // 创建一个缓冲区
                byte[] buffer = new byte[1024 * 1024 * 10];

                int length = -1;
                try
                {
                    length = socketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    break;
                }

                if (length > 0)
                {
                    string msg = string.Empty;
                    msg = Encoding.UTF8.GetString(buffer, 0, length);
                    Console.WriteLine("服务器:" + msg);
                }
                else
                    break;
            }
        }
    }
}

使用

using System;
using System.Collections.Generic;
using System.Text;

namespace SocketDemo
{
    public class MainClient
    {
        SocketClient client;
        public MainClient()
        {
            client = new SocketClient();
            // 建立连接
            client.Connect("127.0.0.1",9997);
            // 发送数据
            client.SendMsg("Hello,小小笔记大大用处");
        }
    }
}