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);
        }
    }
}
相关推荐
时空系39 分钟前
第10篇:继承扩展——面向对象编程进阶 python中文编程
开发语言·python·ai编程
CHANG_THE_WORLD2 小时前
python 批量终止进程exe
开发语言·python
古城小栈2 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
Gary Studio3 小时前
安卓HAL C++基础-智能指针
开发语言·c++
啧不应该啊3 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
zjun10013 小时前
TCP专栏-1.TCP协议概念说明
网络·网络协议·tcp/ip
cen__y4 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
xingpanvip4 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
guygg884 小时前
基于遗传算法的双层规划模型求解MATLAB实现
开发语言·matlab
凯瑟琳.奥古斯特4 小时前
SQLAlchemy核心功能解析
开发语言·python·flask