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);
        }
    }
}
相关推荐
鹿野素材屋5 分钟前
C#中对于List的多种排序方式
开发语言·c#
whxnchy9 分钟前
C++刷题 - 7.27
开发语言·c++
白日梦想家-K1 小时前
题单【模拟与高精度】
开发语言·c++·算法
鹦鹉0071 小时前
IO流中的字节流
java·开发语言·后端
重生之我是Java开发战士1 小时前
【C语言】内存函数与数据在内存中的存储
c语言·开发语言·算法
haaaaaaarry1 小时前
Element Plus常见基础组件(二)
开发语言·前端·javascript
AI_RSER2 小时前
第一篇:【Python-geemap教程(三)上】3D地形渲染与Landsat NDVI计算
开发语言·python·3d·信息可视化·遥感·gee
WSSWWWSSW2 小时前
Python编程基础与实践:Python循环结构基础
开发语言·python
极客BIM工作室2 小时前
深入理解C++中的Lazy Evaluation:延迟计算的艺术
开发语言·c++
im_AMBER2 小时前
学习日志25 python
开发语言·python·学习