首页 > 编程语言 >C#-socket通信实例

C#-socket通信实例

时间:2022-10-30 15:56:39浏览次数:39  
标签:socket C# void private client 实例 new Socket AppendText

使用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

 

标签:socket,C#,void,private,client,实例,new,Socket,AppendText
From: https://www.cnblogs.com/ariter/p/16841443.html

相关文章

  • 关于Implicit super constructor Person() is undefined for default constructor. Mu
    ImplicitsuperconstructorPerson()isundefinedfordefaultconstructor.MustdefineanexplicitconstructorJava(134217868)写继承例题的一个小错误,记一下父类:......
  • 14.docker 15问
    目录什么是Docker?Docker的应用场景有哪些?Docker的优点有哪些?Docker与虚拟机的区别是什么?Docker的三大核心是什么?如何快速安装Docker?如何修改Docker的存储位置?Dock......
  • c# aveva marine 批量导出图纸到dxf格式
    获取图纸数据库查看代码publicstaticDictionary<string,List<DbElement>>GetDbElements(DbTypedbtype){Dictionary<string,List<DbElement......
  • C语言之存储类,枚举,结构体,共用体,typedef
    目录1存储类1.1auto存储类1.2register存储类1.3static存储类1.4extern存储类2枚举2.1定义2.2操作枚举2.2.1用for循环遍历枚举3结构体3.1定义结构3.2操作结构......
  • CSP-S 2022 游记
    前言\(2020\)被儒略日干爆\(2021\)被括号和回文干爆\(2022\)不知道会不会被干爆Day-2某群一张聊天截图,CSP取消。我:???Day-1某群又一张聊天截图,CSP恢复。我:???是......
  • 【C++】右值引用
    来源于:https://zhuanlan.zhihu.com/p/3359943701.什么是右值引用左值可以取地址、位于等号左边。右值没法取地址、位于等号右边。有地址的变量就是左值,没有地址的字面......
  • CSP2022 S游记
    9.26:开坑。没报J组主要是因为J比较垃圾,去抢小朋友的一等没什么意思。初赛刚拿到试卷就直接懵了,这tm是给人做的题?宇宙射线是什么奇妙东西,还有基数排序我根本不会啊......
  • WPF里ItemsControl的分组实现
    一、WPF里ItemsControl的分组实现我们在用到ItemsControl时,有时会用到分组。如下图所示,绑定一个普通一个数组如下所示:数据类型为:publicclassStudent{......
  • python 爬虫 -----selenium自动化测试工具的使用 + Microsoft edge driver 的安装
    selenium的安装python-mpip--default-timeout=100installselenium-ihttp://pypi.douban.com/simple/--trusted-hostpypi.douban.com Microsoftedged......
  • Mac开发_隐藏与显示Dock 上的程序图标
    1、启动时就处理选中target->info,点击任意key值中有个中有个加号,新增Applicationisagent(UIElement)字段,设置值为YES(隐藏)、NO(显示).2、动态调整//应用......