zoukankan      html  css  js  c++  java
  • socket 通信 多线程调用窗体(委托)的几个知识点,记录在案,以备查阅

    1.socket 通信传输汉字的方法:Encoding.GetEncoding("GB2312").GetString(Receivebyte) 发送接收都这样转化

    直接上程序

     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);//委托简单调用
                }
            }
        }

    上面代码仅供参考,有肯多不足,请多指教

    Top
    收藏
    关注
    评论
  • 相关阅读:
    cf------(round)#1 C. Ancient Berland Circus(几何)
    cf------(round)#1 B. Spreadsheets(模拟)
    grep 精确匹配
    解决 service iptables save 报错 please try to use systemctl
    kubernetes 亲和性调度详解
    免费好用的SSH手机客户端
    axios和drf结合的增删改查
    CDH 部署 Hadoop:5.开始安装
    OpenNebula概述
    Python 3.x 引入了函数注释
  • 原文地址:https://www.cnblogs.com/smiler/p/2995641.html
Copyright © 2011-2022 走看看