C# 套接字发送数据接收数据 异步

服务端

在这里插入图片描述

public partial class AsyServerForm2 : Form
    {
    
    
        string ip; // IP地址
        string port; // 端口号
        IPEndPoint endPoint; // 网络端点
        Socket socServer; // 侦听连接套接字
        Socket socClient; // 通讯套接字
        byte[] dataReceived = new byte[1024 * 1024 * 2];

        public AsyServerForm2()
        {
    
    
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        void ShowMsg(string str)
        {
    
    
            txtLog.AppendText(str + "\r\n");
        }

        void StartListen(string ip, string port)
        {
    
    
            this.ip = ip;
            this.port = port;
            socServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            endPoint = new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(port));
            socServer.Bind(endPoint);
            socServer.Listen(0);
            socServer.BeginAccept(new AsyncCallback(OnClientConnect), null);
            ShowMsg("Wait Connect");
        }

        void OnClientConnect(IAsyncResult ar)
        {
    
    
            socClient = socServer.EndAccept(ar);
            WaitForData();
            ShowMsg("Client connect " + socClient.RemoteEndPoint.ToString());
        }

        void WaitForData()
        {
    
    
            if (socClient != null)
            {
    
    
                socClient.BeginReceive(dataReceived, 0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
            }
        }

        void OnDataReceived(IAsyncResult ar)
        {
    
    
            int dataLength = socClient.EndReceive(ar);
            byte[] chars = new byte[dataLength];
            Buffer.BlockCopy(dataReceived,0,chars,0,dataLength);
            string msg = Encoding.UTF8.GetString(chars);
            ShowMsg("client:"+socClient.RemoteEndPoint.ToString()+" : "+msg);
            WaitForData();
        }

        void SendMsg(string msg)
        {
    
    
            byte[] data = Encoding.Default.GetBytes(msg);
            socClient.Send(data);
            ShowMsg("server:"+socServer.RemoteEndPoint.ToString()+" : "+msg);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
    
    
            StartListen(txtServer.Text,txtPort.Text);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
    
    
            SendMsg(txtMsg.Text);
        }
    }

客户端

在这里插入图片描述

public partial class AsyClientForm2 : Form
    {
    
    
        string ip;
        string port;
        IPEndPoint endPoint;
        Socket socClient;
        byte[] dataReceived = new byte[1024 * 1024 * 2];


        public AsyClientForm2()
        {
    
    
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        void Connect(string ip,string port)
        {
    
    
            this.ip = ip;
            this.port = port;
            socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            endPoint = new IPEndPoint(IPAddress.Parse(this.ip),int.Parse(port));
            socClient.BeginConnect(endPoint,new AsyncCallback(OnToConnect),null);
        }

        void OnToConnect(IAsyncResult ar)
        {
    
    
            socClient.EndConnect(ar);
            WaitForData();
            ShowMsg("Connect Success");
        }

        void WaitForData()
        {
    
    
            if (socClient != null)
            {
    
    
                socClient.BeginReceive(dataReceived,0,dataReceived.Length,SocketFlags.None,new AsyncCallback(OnDataReceived),null);
            }
        }

        void OnDataReceived(IAsyncResult ar)
        {
    
    
            int dataLength = socClient.EndReceive(ar);
            byte[] chars = new byte[dataLength];
            Buffer.BlockCopy(dataReceived,0,chars,0,dataLength);
            string msg = Encoding.UTF8.GetString(chars);
            ShowMsg("server:"+msg);
            WaitForData();
        }

        void SendMsg(string msg)
        {
    
    
            byte[] data = Encoding.Default.GetBytes(msg);
            socClient.Send(data);
            ShowMsg("client:"+msg);
        }

        void ShowMsg(string str)
        {
    
    
            txtLog.AppendText(str + "\r\n");
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
    
    
            Connect(txtServer.Text,txtPort.Text);

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
    
    
            SendMsg(txtMsg.Text);
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_41841482/article/details/114441438