Esempio n. 1
0
        private void Btnsend_Click(object sender, EventArgs e)
        {
            string strsend = sendtext.Text.Trim();

            if (string.IsNullOrEmpty(strsend) || pclist.CheckedItems.Count <= 0)
            {
                MessageBox.Show("消息为空或未选择发送人");
                return;
            }
            PcMsg pm = new PcMsg
            {
                sendpcname = pcname.Text,
                msg        = strsend
            };

            for (int i = 0; i < pclist.CheckedItems.Count; i++)
            {
                DataRowView drv = pclist.CheckedItems[i] as DataRowView;
                pm.pcname.Add(new PcName(drv["guid"].ToString(), drv["name"].ToString()));
            }
            byte[] buffter = Encoding.UTF8.GetBytes(pm.SerializeObject());
            try
            {
                int temp = socketClient.Send(buffter);
                //msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + pm.sendpcname + " 说: " + strsend + System.Environment.NewLine);
                sendtext.Clear();
            }
            catch (Exception ex)
            {
                msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.Message + System.Environment.NewLine);
            }
        }
Esempio n. 2
0
        private void Btnconnect_Click(object sender, EventArgs e)
        {
            try
            {
                serverip     = tbserverip.Text.Trim();
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socketClient.Connect(serverip, 8009);
                PcMsg pm = new PcMsg
                {
                    sendpcname = pcname.Text,
                    msg        = pcname.Text,
                    notice     = false
                };
                socketClient.Send(Encoding.UTF8.GetBytes(pm.SerializeObject()));
                TextBox.CheckForIllegalCrossThreadCalls = false;

                thread = new Thread(Recive)
                {
                    IsBackground = true
                };
                thread.Start(socketClient);

                btnsend.Enabled    = true;
                sendtext.Enabled   = true;
                btnstop.Enabled    = true;
                btnconnect.Enabled = false;
                pcname.Enabled     = false;
                msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接服务成功" + System.Environment.NewLine);
            }
            catch (Exception ex)
            {
                msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.Message + System.Environment.NewLine);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 监听连接
        /// </summary>
        /// <param name="o"></param>
        static void Listen(object o)
        {
            Socket serverSocket = o as Socket;

            while (true)
            {
                try
                {
                    //等待连接并且创建一个负责通讯的socket
                    Socket con = serverSocket.Accept();

                    //获取连接的PcName
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    con.ReceiveTimeout = 1000;
                    int    effective = con.Receive(buffer);
                    string json      = string.Empty;
                    if (effective > 0)
                    {
                        json = Encoding.UTF8.GetString(buffer, 0, effective);
                    }
                    PcMsg pm = PcMsg.DeserializeJosn(json);
                    if (pm == null || pm.notice)
                    {
                        //con.Close();
                        continue;
                    }
                    string pcname = pm.msg;
                    //将该Pc加入到连接列表中
                    String guid = Guid.NewGuid().ToString();
                    skAll.Add(guid, new GuidSocket(pcname, con));
                    Updatepc();

                    //获取链接的IP地址
                    String sendIpoint = con.RemoteEndPoint.ToString();
                    Console.WriteLine("已连接客户端:" + pcname + ", 地址: " + sendIpoint);

                    //开启一个新线程不停接收消息
                    Thread thread = new Thread(Recive)
                    {
                        IsBackground = true
                    };
                    thread.Start(guid);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Listen错误:" + ex.Message);

                    //服务端强制关闭连接
                    if (ex is SocketException skex && skex.ErrorCode == 10054)
                    {
                        //return;
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="o"></param>
        static void Recive(object o)
        {
            String guid = o as String;

            while (true)
            {
                try
                {
                    //获取发送过来的消息容器
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    skAll[guid].socket.ReceiveTimeout = 0;
                    int effective = skAll[guid].socket.Receive(buffer);
                    //有效字节为0则跳过
                    if (effective == 0)
                    {
                        break;
                    }
                    String json = Encoding.UTF8.GetString(buffer, 0, effective);
                    PcMsg  pm   = PcMsg.DeserializeJosn(json);
                    if (pm == null)
                    {
                        Console.WriteLine("用户非法访问: " + skAll[guid].socket.RemoteEndPoint);
                        skAll[guid].socket.Close();
                        skAll.Remove(guid);
                        break;
                    }
                    if (pm.notice)
                    {
                        string nexuser = string.Empty;
                        pm.sendpcname = skAll[guid].name;
                        foreach (PcName pnTemp in pm.pcname)
                        {
                            skAll[pnTemp.guid].socket.Send(Encoding.UTF8.GetBytes(pm.SerializeObject()));
                            nexuser += (string.IsNullOrEmpty(nexuser) ? "" : "、") + pnTemp.name;
                        }
                        Console.WriteLine("用户" + skAll[guid].name + "向" + nexuser + " 发送了消息:" + pm.msg);
                    }
                    else
                    {
                        Console.WriteLine(json);
                    }
                }
                catch (Exception ex)
                {
                    //服务端强制关闭连接
                    if (ex is SocketException skex && skex.ErrorCode == 10054)
                    {
                        Console.WriteLine("Recive 客户端: " + skAll[guid].name + ", 地址: " + skAll[guid].socket.RemoteEndPoint + "已经退出" + ", " + ex.Message);
                    }
Esempio n. 5
0
        private static void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                //获取连接的PcName
                byte[] buffer    = e.Buffer;
                int    effective = buffer.Length;
                string json      = string.Empty;
                if (effective > 0)
                {
                    json = Encoding.UTF8.GetString(buffer, 0, effective);
                }
                PcMsg pm = PcMsg.DeserializeJosn(json);
                if (pm == null || pm.notice)
                {
                    return;
                }
                string pcname = pm.msg;
                //将该Pc加入到连接列表中
                String guid = Guid.NewGuid().ToString();
                skAll.Add(guid, new GuidSocket(pcname, e.AcceptSocket));
                Updatepc();

                //获取链接的IP地址
                String sendIpoint = e.AcceptSocket.RemoteEndPoint.ToString();
                Console.WriteLine("已连接客户端:" + pcname + ", 地址: " + sendIpoint);

                //开启一个新线程不停接收消息
                Thread thread = new Thread(Recive)
                {
                    IsBackground = true
                };
                thread.Start(guid);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Listen错误:" + ex.Message);

                //服务端强制关闭连接
                if (ex is SocketException skex && skex.ErrorCode == 10054)
                {
                    //return;
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="o"></param>
        public void Recive(object o)
        {
            var send = o as Socket;

            while (true)
            {
                //获取发送过来的消息
                byte[] buffer = new byte[1024 * 1024 * 2];
                try
                {
                    var effective = send.Receive(buffer);
                    if (effective == 0)
                    {
                        break;
                    }
                    string json = Encoding.UTF8.GetString(buffer, 0, effective);
                    PcMsg  pm   = PcMsg.DeserializeJosn(json);
                    if (pm.notice)
                    {
                        this.msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss  ") + pm.sendpcname + ":" + pm.msg + System.Environment.NewLine);
                    }
                    else
                    {
                        this.pclist.DataSource    = pm.GetPcNameDt();
                        this.pclist.DisplayMember = "name";
                        this.pclist.ValueMember   = "guid";
                    }
                }
                catch (Exception ex)
                {
                    this.msgtext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.Message + System.Environment.NewLine);
                    //服务端强制关闭连接
                    if (ex is SocketException skex && skex.ErrorCode == 10054)
                    {
                        return;
                    }
                }
            }
        }