TCP异步通信_服务端

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

namespace TcpServerAsync
{
    class ServerSocket
    {
        public Socket socket;
        public Dictionary clientDic = new Dictionary();
        public void Start(string ip,int port,int num)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip),port);
            try
            {
                socket.Bind(ipPoint);
                socket.Listen(num);
                //通过异步接收客户端连入
                socket.BeginAccept(AcceptCallBack,null);
            }
            catch (Exception e)
            {
                Console.WriteLine("启动服务器失败" + e.Message);
            }
          
        }
        private void AcceptCallBack(IAsyncResult result)
        {
            try
            {
                //获取连入的客户端
                Socket clientSocket = socket.EndAccept(result);
                ClientSocket client = new ClientSocket(clientSocket);
                //记录客户端对象
                clientDic.Add(client.clientID ,client);
            }
            catch (Exception e)
            {
                Console.WriteLine("客户端连接失败" + e.Message);
            }
        }
        public void Broadcast(string str)
        {
            foreach (ClientSocket client  in clientDic .Values)
            {
                client.Send(str);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TcpServerAsync
{
    class ClientSocket
    {
        public Socket socket;
        public int clientID;
        public static int CLIENT_BEGIN_ID = 1;
        byte[] receiveBytes = new byte[1024];
        int cacheNum = 0;

        public ClientSocket (Socket socket)
        {
            socket = this.socket;
            clientID = CLIENT_BEGIN_ID++;
        
            //开始收消息
            socket.BeginReceive(receiveBytes, cacheNum, receiveBytes.Length,SocketFlags.None,ReceiveCallBack,null);
        }
        private void ReceiveCallBack(IAsyncResult result)
        {
            try
            {
                cacheNum= this.socket.EndReceive(result);
                Console .WriteLine ( Encoding.UTF8.GetString(receiveBytes, 0, cacheNum));
                //继续接收消息
                cacheNum = 0;
                //判断是否是连接状态
                if (this.socket.Connected)
                    this.socket.BeginReceive(receiveBytes, cacheNum, receiveBytes.Length, SocketFlags.None, ReceiveCallBack,null);
                else
                    Console.WriteLine("没有连接,不用发消息了");
            }
            catch (SocketException e)
            {
                Console.WriteLine("连接错误" + e.SocketErrorCode + e.Message);
            }
        }
        public void Send(string str)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            this.socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None,SendCallBack, null);
        }
        private void SendCallBack(IAsyncResult result)
        {
            try
            {
                this.socket.EndSend(result);
            }
            catch (SocketException e)
            {
                Console.WriteLine("发送错误" + e.SocketErrorCode + e.Message);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TcpServerAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.Start("127.0.0.1", 8080, 1024);
            Console.WriteLine("开启服务器成功");
            while (true)
            {
                string input = Console.ReadLine();
                if(input .Substring (0,2)=="B:")
                {
                    serverSocket.Broadcast(input.Substring(2));
                }
            }
        }
    }
}

你可能感兴趣的:(Unity网络开发基础,tcp/ip,网络协议,网络)