服务端Socket(同步方式)

刘星火
2023-12-01
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ServerTest
{
    internal class Program
    {
        static Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static void Main(string[] args)
        {
            int port = 8885;
            InterceptionToClients(ServerSocket, port, 10);

            Thread acceptThraed = new Thread(AcceptThread);
            acceptThraed.Start();

            Console.ReadKey();
        }

        /// <summary>
        /// 服务端侦听客户端
        /// </summary>
        /// <param name="port">进程端口号</param>
        /// <param name="listenCount">设置排队连接的请求个数</param>
        private static void InterceptionToClients(Socket serverSocket,int port, int listenCount)
        {
            IPAddress ip = IPAddress.Any;  // 侦听所有网络客户接口的客户端
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            serverSocket.Bind(endPoint);
            serverSocket.Listen(listenCount);  //设定最多有10个排队连接请求
            Console.WriteLine("建立连接");
        }

        /// <summary>
        /// 子线程,负责监听用户的上线连接.
        /// </summary>
        private static void AcceptThread()
        {
            while (true)
            {
                Console.WriteLine("开始接收Socket");
                Socket socket = ServerSocket.Accept();
                Console.WriteLine($"客户端{socket.RemoteEndPoint.ToString()}:已上线!");
                Thread receiveThread = new Thread(ReceiveThread);
                receiveThread.Start(socket);        //注意这里要开启一个新的子线程,找了好久的bug
            }
        }

        /// <summary>
        /// 子线程,循环接收用户发送过来的消息.
        /// </summary>
        /// <param name="obj"></param>
        private static void ReceiveThread(object obj)
        {
            Socket socket = (Socket)obj;
            int arrayLength = 1024;
            while (true)
            {
                try
                {
                    Console.WriteLine("-------");
                    ReceiveMsgFromClient(socket, arrayLength);
                    SendMsgToClient(socket, $"成功接收来自{socket.RemoteEndPoint.ToString()}的消息");
                }
                catch (Exception)
                {
                    Console.WriteLine($"客户端{socket.RemoteEndPoint.ToString()}已下线");
                    CloseSocket(socket);    
                    break;
                }
            }
        }

        /// <summary>
        /// 接收来自客户端的消息
        /// </summary>
        /// <param name="clientSocket">客户端的socket</param>
        /// <param name="arrayLength">定义字节数组最大长度</param>
        /// <returns>返回接收到的消息的字节数组长度</returns>
        private static int ReceiveMsgFromClient(Socket clientSocket, int arrayLength)
        {
            byte[] receive = new byte[arrayLength];
            int length = clientSocket.Receive(receive);
            Console.WriteLine($"接收到来自{clientSocket.RemoteEndPoint.ToString()}的消息:{Encoding.UTF8.GetString(receive)}");
            if (length == 0)
            {
                return 0;
            }
            return length;
        }
        
        /// <summary>
        /// 发送消息至客户端
        /// </summary>
        /// <param name="socket">客户端的socket</param>
        /// <param name="str">要发送的消息</param>
        private static void SendMsgToClient(Socket socket, string str)
        {
            byte[] send = Encoding.UTF8.GetBytes(str);
            socket.Send(send);
            Console.WriteLine("发送消息为:" + Encoding.UTF8.GetString(send));
        }

        /// <summary>
        /// 关闭socket
        /// </summary>
        /// <param name="socket">要关闭的socket</param>
        private static void CloseSocket(Socket socket)
        {
            socket.Close();
        }
    }
}

 类似资料: