winform下Socket通信的简单应用

今天给大家来讲解下socket通信的原理,通常socket通信分为TCP,UDP两种不同的用法,我把两种方法都写出来了。

先看效果图:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace APP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
  /******************************************
   * 
   * 利用Socket通讯,TCP和UDP的不同用法
   * TCP:面向连接,三次握手,数据安全性较高
   * UDP:面向无连接,数据易丢失,安全性不高
   * 
   ******************************************/

        //启动服务端
        Socket SocketUdp;
        Socket SocketTcp;
        delegate void SetTextCallBack(string text);
        //这个是启动服务端的按钮,在启动服务端后,会根据客户端发送回来的信息请求,自动将信息显示在文本框上
        private void button1_Click(object sender, EventArgs e)
        {
            //UDP类型
            SocketUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            EndPoint ep = new IPEndPoint(IPAddress.Any, 3000);
            SocketUdp.Bind(ep);//绑定本机IP和Port
            Thread th = new Thread(new ThreadStart(ReceiveMsg));
            th.IsBackground = true;
            th.Start();
            label2.Text = "服务器已启动";
            button1.Enabled = false;


            TCP类型
            //SocketTcp = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            //EndPoint ep = new IPEndPoint(IPAddress.Any, 3000);
            //SocketTcp.Bind(ep);
            //SocketTcp.Listen(2000);
            //Thread th = new Thread(new ThreadStart(ReceiveMsg));
            //th.IsBackground = true;
            //th.Start();
            //label2.Text = "服务器已启动";
            //button1.Enabled = false;
        }
        public void ReceiveMsg()
        {
            while (true)
            {
                byte[] buffer = new byte[5555];
                EndPoint ep = new IPEndPoint(IPAddress.Any, 3000);
                int lea = SocketUdp.ReceiveFrom(buffer, ref ep);//接收远程;
                string msg = Encoding.Unicode.GetString(buffer, 0, lea);
                SetText(msg);
            }


            //while(true)
            //{
            //    Socket client = SocketTcp.Accept();
            //    byte[] buffer=new byte[1024];
            //    int lea = client.Receive(buffer);//接收远程;
            //    string msg = Encoding.Unicode.GetString(buffer, 0, lea);
            //    SetText(msg);
            //    client.Close();
            //}
        }
        public void SetText(string text)
        {   
            //在这里,我强调一下,为什么我会用invoke呢,或许很多人对此不太了解,如果不用的话,会报错。我会另外抽时间给大家讲解下invoke,beigninvoke,多线程,委托与事件之间的联系的,反正大家先这么写着。
            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 button2_Click(object sender, EventArgs e)
        {
            if (button1.Enabled ==true)
            {
                MessageBox.Show("服务端未启动,请先启动服务器!");
            }
            else
            {
                string msg = richTextBox2.Text;
                string ip = textBox1.Text;

                //UDP
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                byte[] buffer = Encoding.Unicode.GetBytes(msg);
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 3000);
                client.SendTo(buffer, buffer.Length, SocketFlags.None, ipe);
                MessageBox.Show("发送成功!");


                TCP
                //Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 3000);
                //client.Connect(ipe);
                //byte[] buffer = Encoding.Unicode.GetBytes(msg); 
                //client.Send(buffer);
                //MessageBox.Show("发送成功!");
                
            }
        }
    }
}

好了,基本上的通信完成了。有什么不懂的问我。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值