17-C#的socket通信TCP-1

-C#的socket通信TCP

1.

csharp 复制代码
namespace WindowsFormsApp1
{


    delegate void adduserinfodel(string userinfo);//创建委托
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            mydel += addnf;
            textBox1.Text = "192.168.0.6";
            textBox2.Text = "666";
        }

        adduserinfodel mydel;
        Thread th;
        Socket _socket;

        private void button1_Click(object sender, EventArgs e)
        {
            _socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            IPAddress address = IPAddress.Parse(this.textBox1.Text.Trim());
            IPEndPoint endPoint = new IPEndPoint(address,Convert.ToInt32(this.textBox2.Text.Trim()));

            try 
            {
                _socket.Bind(endPoint);
                MessageBox.Show("创建OK");
            }
            catch(Exception ex) 
            {
                MessageBox.Show("创建失败");

            }  
            _socket.Listen(100);

            th = new Thread(listenfuntion);
            th.Start();
        }

        private void listenfuntion()
        {
            while (true)
            {
               Socket socketclient= _socket.Accept();
                string info = socketclient.RemoteEndPoint.ToString();
                Invoke(mydel, info);

                Thread th = new Thread(receiveinfo);
                th.IsBackground = true;
                th.Start(socketclient);
            }
        }

        private void receiveinfo(object obj)
        {
            Socket sckclient = obj as Socket;
            if (sckclient != null)
            {
                byte[] arr = new byte[1024 * 1024 * 5];
                int len = -1;
                len = sckclient.Receive(arr);
                if (len == 0) 
                {
                

                }
                else
                {

                    //textBox3.Text=Encoding.UTF8.GetString(arr,0, len);
                }

            }
        }

        private void addnf(string a)
        {
            listBox1.Items.Add(a);
        }
    }
}
相关推荐
hez20101 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
MrSYJ4 天前
TCP协议理解
后端·tcp/ip
雨落倾城夏未凉7 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫8 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫9 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6259 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902119 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech12 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf