UDP通信:用C#编写winform聊天程序

先看下实现效果:
在这里插入图片描述

基础知识参考:https://blog.csdn.net/subin_iecas/article/details/80289513

UDP是一个非连接的协议,传输数据之前源端和终端不建立连接,双方没有专有的通信通道。当发送端想传送数据时就简单地把数据扔到网络上,并不能保证他们能到达目的地。接收端由于没有与发送端建立专用的通信通道,因此接收数据时并不能确定是有谁发来的数据。

因此,在socket编程中UDP不需要进行连接,只要知道对方的IP和端口就能进行通信。UDP通信没有服务器和客户端之分,每台主机都是平等的。因此,进行通信的每个进程的代码是可以一模一样的。
在这里插入图片描述

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

namespace UDP_Host_B
{
    public partial class Form1 : Form
    {
        private static Socket socket;
        private static IPEndPoint port;
        private static EndPoint remote_port;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPAddress ip = IPAddress.Parse(tbox_local_IP.Text);
                port = new IPEndPoint(ip, Convert.ToInt32(tbox_local_port.Text));
                socket.Bind(port);

                IPAddress remote_IP = IPAddress.Parse(tbox_remote_IP.Text);
                remote_port = new IPEndPoint(remote_IP, Convert.ToInt32(tbox_remote_port.Text));
                display_msg("启动聊天");

                Thread th = new Thread(receive_msg);
                th.IsBackground = true;
                th.Start();
            }
            catch { }
        }

        void receive_msg()
        {
            while (true)
            {
                EndPoint received_port = new IPEndPoint(IPAddress.Any, 0);
                byte[] buffer = new byte[1024 * 1024 * 5];
                int len = socket.ReceiveFrom(buffer, ref received_port);  // 将接收消息的端口信息保存在第二个参数中
                string msg = Encoding.UTF8.GetString(buffer, 0, len);
                display_msg(remote_port.ToString() + ":" + msg);
            }
        }

        void send_msg()
        {
            try
            {
                string msg = tbox_send.Text;
                socket.SendTo(Encoding.UTF8.GetBytes(msg), remote_port);
                display_msg("我" + ":" + msg);
                tbox_send.Clear();
            }
            catch { }
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            send_msg();
        }

        private void tbox_send_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                send_msg();
            }
        }

        void display_msg(string s)
        {
            tbox_display.AppendText(s + "\r\n");
        }
    }
}

将上述代码实例化两次,分配不同的端口,即可在同一台主机上通信;或者设置IP和端口在两台主机上通信。这里给出示例代码的具体工程,点击下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值