socket学习 同步

socket分为2种模式,同步和异步,

同步:

服务器端

建立联接,首先声明一个全局的Socket,这个必须是全局的,因为其他的地方还需要使用这个实例。

Socket socket;

建立监听

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.200.212"), 1234);

            socket.Bind(ipEndPoint);

            socket.Listen(10);

这样就建立了允许最多10个用户的监听,

 

然后建立线程监听获得的消息

 Thread t = new Thread(StartListener);

            t.IsBackground = true;

            t.Start();

这个线程是为了接收多个客户端联接。

 

以上代码可以放到Page_load里,或者放到服务器的启动按钮里。

  private void StartListener()
        {
            while (true)
            {
                byte[] packBuff = new byte[maxSize];

                Socket newClient =socket.Accept();

                newClient.Receive(packBuff);

                string ip = Encoding.UTF8.GetString(packBuff).TrimEnd('/0');

                ht.Add(ip, newClient);//这里是把联接的客户端更新下,不影响核心逻辑

                UpdateOnlineUserList(ip, true);//这里是把联接的客户端更新下,不影响核心逻辑

                System.Threading.Thread t = new System.Threading.Thread(new ParameterizedThreadStart(ReceivedMsg));

                t.IsBackground = true;
                t.Start(ip);
            }
           
        }

在监听线程里把链接的客户端保存起来,同时建立一个线程来启动接收数据

 private void ReceivedMsg(object userName)
        {
            while (true)
            {
                Socket clientSocket = ht[userName] as Socket;

                byte[] buff = new byte[128];

                clientSocket.Receive(buff);

                string message = Encoding.UTF8.GetString(buff).TrimEnd('/0');

                if (message == "")
                {
                    continue;
                }
                string flag = message.Substring(0, 2);
                this.Invoke((EventHandler)delegate
                {
                    lstReceiveMsg.Items.Add(message + "_"+flag+"_" + userName);

                });

                switch (flag)
                {
                    case"01":
                        ht.Remove(userName);
                        UpdateOnlineUserList(userName.ToString(),false);
                        Thread.CurrentThread.Abort();
                        break;
                   
                    default:
                      
                        string ip = message.Split('#')[0];

                        if (ht.ContainsKey(ip))
                        {
                            this.Invoke((EventHandler)delegate
                            {
                                lstReceiveMsg.Items.Add("Send " + ip + " Say:" + message.Split('#')[1]);

                            });
                            Socket talkSocke = ht[ip] as Socket;

                            talkSocke.Send(Encoding.UTF8.GetBytes(userName.ToString()+" Say:"+message.Split('#')[1]));

                        }
                        break;
                }
            }
        }

这里接收到数据,同时进行处理,

 

客户端:

 

建立联接,首先声明一个全局的Socket,这个必须是全局的,因为其他的地方还需要使用这个实例。

Socket socket;

建立连接

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.200.212"), 1234);

              socket.Connect(ipEndPoint);

 

新建线程来获取接收数据

            Thead  t = new Thread(ReceivedMsg);

            t.IsBackground = true;

            t.Start();

以上代码可以放到Page_load或者联接按钮里。

 


        private void ReceivedMsg()
        {
            while (true)
            {
                byte[] b = new byte[1024*60];

                socket.Receive(b);

                string message = Encoding.UTF8.GetString(b).TrimEnd('/0');
               }

         }

这里是解决接收数据的线程。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值