socket 通信 多线程调用窗体(委托)

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //定义委托
        public delegate void ShowMessageHandel(string msg);
        //向控件添加显示信息
        public void showMsg(string msg)
        {
            listBox1.Items.Add(msg);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //Control.CheckForIllegalCrossThreadCalls = false;
            Thread th = new Thread(new ThreadStart(ServerSocket));
            th.Start();
            // ServerSocket();
        }
        Socket client;
        public void ServerSocket()
        {
            IPEndPoint ipP = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 6000);
            Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketServer.Bind(ipP);
            while (true)
            {
                socketServer.Listen(5);
                client = socketServer.Accept();
                Thread thClient = new Thread(new ThreadStart(ClientSocket));
                thClient.Start();
            }
        }
        public void ClientSocket()
        {
            ShowMessageHandel smh = showMsg;
              
            byte[] byteMsg = new byte[1024];
            while (true)
            {
                client.Receive(byteMsg, byteMsg.Length, SocketFlags.None);
                client.Send(System.Text.ASCIIEncoding.UTF8.GetBytes("你好"));
                client.Send(UTF8Encoding.GetEncoding("GB2312").GetBytes("你好"));
                // listBox1.Items.Add(Encoding .ASCII.GetString(byteMsg));
                //可收发汉字
                string strMsg = UTF8Encoding.GetEncoding("GB2312").GetString(byteMsg);
                this.BeginInvoke(smh, strMsg);//委托简单调用
            }
        }
    }


知识共享许可协议
《socket 通信 多线程调用窗体(委托)》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     156.85ms