基本信息
源码名称:C#多线程以及Socket通讯示例源码
源码大小:0.67M
文件格式:.rar
开发语言:C#
更新时间:2020-09-07
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍


   void Listen(object obj)
        {

            Socket socketWatch = obj as Socket;
            while (true)
            {
                try
                {
                    //等待客户端的连接,同时会创建一个与其通信的socket
                    socketCommunication = socketWatch.Accept();
                    clientCommunicationSocketList.Add(socketCommunication);
                    dicSocket.Add(socketCommunication.RemoteEndPoint.ToString(), socketCommunication);
                    //cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString());
                    //解决跨线程访问cboUsers所导致的问题
                    if(cboUsers.InvokeRequired)
                    {
                        cboUsers.Invoke(new Action(() => { cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString()); }), null);
                    }
                    else
                    {
                        cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString());
                    }
                    ShowMsg(socketCommunication.RemoteEndPoint.ToString() ":连接成功");
                    Thread thread = new Thread(Receive);
                    thread.IsBackground = true;
                    thread.Start(socketCommunication);
                }
                catch
                {

                }

            }
        }
        void Receive(object obj)
        {
            Socket socketCommunication = obj as Socket;
            byte[] buffer = new byte[1024 * 1024 * 2];
            while (true)
            {
                try
                {

              
                //r表示实际接收到的字节数
                int r = socketCommunication.Receive(buffer);
                if(r==0)
                {
                    //break;
                    socketCommunication.Shutdown(SocketShutdown.Both);
                    socketCommunication.Close();

                    return;
                }
                string str = Encoding.UTF8.GetString(buffer, 0, r);
                //显示消息格式:客户端IP 端口:消息
                ShowMsg(socketCommunication.RemoteEndPoint.ToString() ":" str);
                }
                catch
                {

                }
            }
            
        }
        void ShowMsg(string str)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action<string>(s =>
                {
                    txtLog.AppendText(s "\r\n");
                }), str);
            }
            else
            {
                //txtLog.Text = str "\r\n" txtLog.Text;
                txtLog.AppendText(str "\r\n");
            }
        }