C# winform socket 通讯

服务端

 服务端代码

        Socket client_socket;
        Socket serversocket;
        Socket testsocket;
        private Thread thread;
        private Thread th_c;
        delegate void SetTextCallBack(string text);
        public FrmMain()
        {
            InitializeComponent();
            client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ;
        }

 

      private void button4_Click(object sender, EventArgs e)
        {
            
            EndPoint ep = new IPEndPoint(IPAddress.Any, Convert.ToInt32(txtserverport.Text));
            serversocket.Bind(ep);
            serversocket.Listen(10);         
            thread = new Thread(new ThreadStart(ReceiveMsg));
            thread.IsBackground = true;
            thread.Start();
            richTextBox1.Text += "服务启动了\n";
        }    

        public void ReceiveMsg()
        {
            while (true)
            {                
                Socket socClient = serversocket.Accept();
                SetText(socClient.RemoteEndPoint.ToString()+ "已经连接");
                ParameterizedThreadStart pts = new ParameterizedThreadStart(HandleClientComm);
                Thread thread = new Thread(pts);
                thread.IsBackground = true;
                thread.Start(socClient);                
            }
        }

        private void HandleClientComm(object client) {
            Socket tcpClient = (Socket)client;
            testsocket = tcpClient;
            byte[] buffer = new byte[1024];
            int lea;                     
            while (true) {
                lea = 0;
                lea = tcpClient.Receive(buffer);//接收远程;
                string msg = Encoding.UTF8.GetString(buffer, 0, lea);
                SetText(msg);
                tcpClient.Send(Encoding.UTF8.GetBytes("我收到了"));

            }
        }

        public void SetText(string text)
        {
        
            //委托方法一
            this.Invoke(new Action(() =>
            {
                richTextBox1.Text += DateTime.Now.ToString() + "\n" + text + "\n";
            }));

            //委托方法二
            //if (richTextBox1.InvokeRequired)
            //{
            //    SetTextCallBack st = new SetTextCallBack(SetText);
            //    this.Invoke(st, new object[] { text });

            //}
            //else
            //{
            //    richTextBox1.Text += DateTime.Now.ToString() + "\n" + text + "\n";
            //}
        }

客户端

  private void button1_Click(object sender, EventArgs e)
        {
            if (client_socket.Connected)
                return;

            IPAddress ipAdress = IPAddress.Parse(textBox1.Text);
            IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, Convert.ToInt32(textBox2.Text));
            try
            {
               client_socket.Connect(ipEndpoint);
               rtbclient.AppendText(DateTime.Now.ToString() + "\n" + "连接成功!" + "\n");
               th_c = new Thread(C_ReceiveMsg);
               th_c.IsBackground = true;
               th_c.Start();
            }
            catch (Exception)
            {
                MessageBox.Show("连接出错,请确认服务器端是否打开。");
            }               
         
        }

        private void C_ReceiveMsg()
        {
            byte[] buffer = new byte[1024];
            int lea;
            while (true)
            {
                lea = 0;
                lea = client_socket.Receive(buffer);//接收远程;
                string msg = Encoding.UTF8.GetString(buffer, 0, lea);
                this.Invoke(new Action(()=> {
                    rtbclient.Text += msg+"\n";
                }));
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (!client_socket.Connected){
                MessageBox.Show("请先连接服务!");
                return;
            }
            string strjson = "这是我的测试";              
            client_socket.Send(Encoding.UTF8.GetBytes(strjson));
            rtbclient.AppendText(DateTime.Now.ToString() + "\n" + strjson + "\n");

        }

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值