C#-socket通信实例

使用socket写一个通信demo

public partial class Form1 : Form
    {
        Socket socketServer;
        IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9027);
        public static bool isOpen = false;
        Dictionary<String, Socket> clientSockets = new Dictionary<string, Socket>();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 开启连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketServer.Bind(ipe);
            socketServer.Listen(10);
            AppendText("服务端已开启,等待客户接入。。。");
            isOpen = true;
            StartListen();
            button2.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            isOpen = false;
            foreach (var s in clientSockets)
            {
                CloseClient(s.Value);
            }
            clientSockets.Clear();
            socketServer.Close();
            AppendText($"服务端已关闭");
            button1.Enabled = true;
        }

        private void StartListen()
        {
            Task.Run(() =>
            {
                while (isOpen)
                {
                    try
                    {
                        // 接受到client连接
                        Socket client = socketServer.Accept();
                        AppendText($"客户端{client.RemoteEndPoint}已接入");
                        clientSockets.Add(client.RemoteEndPoint.ToString(), client);
                        RefreshViewLine();
                        StartReceive(client);
                    }
                    catch (Exception)
                    {
                        isOpen = false;
                    }
                }
            });
        }

        private void StartReceive(Socket client)
        {
            Task.Run(() =>
            {
                string name = client.RemoteEndPoint.ToString();
                while (client.Connected)
                {
                    try
                    {
                        byte[] recByte = new byte[1024 * 3];
                        int len = client.Receive(recByte, recByte.Length, 0);
                        if (len == 0)
                        {
                            CloseClient(client, name);
                            return;
                        }
                        string msg = Encoding.UTF8.GetString(recByte,0, Math.Min(len, recByte.Length)).Trim();
                        AppendText(client.RemoteEndPoint.ToString() + ": " + msg);
                    }
                    catch (Exception ex)
                    {
                        CloseClient(client, name);
                    }
                }
            });
        }

        private void AppendText(string text)
        {
            this.Invoke(new Action(() =>
            {
                txtRecive.AppendText(text + Environment.NewLine);
            }));
        }
        private void CloseClient(Socket client, string name = "")
        {
            if (client != null)
            {
                client.Close();
            }
            if (!string.IsNullOrWhiteSpace(name))
                AppendText(name + ": 客户已下线");
            RefreshViewLine();
        }

        private void RefreshViewLine()
        {
            this.Invoke(new Action(() =>
            {
                this.listView1.Items.Clear();
            }));
            int i = 1;
            foreach (var c in clientSockets)
            {
                if (c.Value.Connected)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = i.ToString();
                    lvi.SubItems.Add(c.Value.RemoteEndPoint.ToString());
                    this.Invoke(new Action(() =>
                    {
                        this.listView1.Items.Add(lvi);
                    }));
                    i++;
                }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSend.Text) && listView1.FocusedItem!=null)
            {
                string clientName = listView1.FocusedItem.SubItems[1].Text.Trim();
                if (clientSockets.ContainsKey(clientName))
                {
                    byte[] sendBytes = Encoding.UTF8.GetBytes(txtSend.Text);
                    clientSockets[clientName].Send(sendBytes);
                    AppendText($"已发送消息到{clientName}:" + txtSend.Text);
                }
                else
                {
                    AppendText($"未发现客户端:{clientName}");
                }
            }
        }
    }
View Code

 

 

 

 

 

 public partial class Form1 : Form
    {
        Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9027);
        Socket clientSocket;
        bool isOpen = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                btnOpen.Enabled = false;
                isOpen = true;
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(ipe);
                btnClose.Enabled = true;
                AppendText("连接成功");
                StartReceive(clientSocket);
            }
            catch (Exception ex)
            {
                AppendText(ex.ToString());
                CloseClient(clientSocket);
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                btnOpen.Enabled = true;
                btnClose.Enabled = false;
                CloseClient(clientSocket);
            }
            catch (Exception ex)
            {
                AppendText(ex.ToString());
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSend.Text))
            {
                byte[] sendBytes = Encoding.UTF8.GetBytes(txtSend.Text);
                clientSocket.Send(sendBytes);
                AppendText("已发送消息:" + txtSend.Text);
            }
        }



        private void AppendText(string text)
        {
            this.Invoke(new Action(() =>
            {
                txtRecive.AppendText(text + Environment.NewLine);
            }));
        }

        private void StartReceive(Socket client)
        {
            Task.Run(() =>
            {
                while (client.Connected)
                {
                    try
                    {
                        byte[] recByte = new byte[4096];
                        int len = client.Receive(recByte, recByte.Length, 0);
                        if (len == 0)
                        {
                            CloseClient(client);
                            return;
                        }
                        string msg = Encoding.UTF8.GetString(recByte, 0, Math.Min(len, recByte.Length)).Trim();
                        AppendText(client.RemoteEndPoint.ToString() + ": " + msg);
                    }
                    catch (Exception)
                    {
                        CloseClient(client);
                    }
                }
            });
        }

        private void CloseClient(Socket client)
        {
            if (isOpen)
            {
                client.Close();
                isOpen = false;
                AppendText("连接已关闭");
                this.Invoke(new Action(() =>
                {
                    btnOpen.Enabled = true;
                    btnClose.Enabled = false;
                }));
            }
        }
    }
View Code

 

posted @ 2022-10-30 15:47  Ariter  阅读(59)  评论(0编辑  收藏  举报