首页 新闻 会员 周边 捐助

C# UdpClient 本机发给本机的UDP消息,WireShark抓不到包

0
悬赏园豆:10 [已关闭问题] 关闭于 2021-03-03 17:46

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace UDP
{
    public partial class Form1 : Form
    {
        private bool IsHandle = true;
        private UdpClient udp;
        private int length = 0;
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            ReceiveMsg();
        }

        private void ReceiveMsg()
        {
            udp = new UdpClient(26666, AddressFamily.InterNetwork);
            Thread thread = new Thread(HandleUdpMsg);
            thread.IsBackground = true;
            IsHandle = true;
            thread.Start();
        }

        private void HandleUdpMsg()
        {
            while (IsHandle)
            {
                IPEndPoint endPoint = null;
                byte[] buffer = udp.Receive(ref endPoint);
                string content = Encoding.UTF8.GetString(buffer);
                chatContentText.AppendText(endPoint.Address + ":\n\t" + content + "\n");
                length += buffer.Length;
                label3.Text = "共计收到\t" + length + "\tbyte";
            }
            udp.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsHandle = false;
        }

        private void MsgSendBtn_Click(object sender, EventArgs e)
        {
            string text = sendMsgText.Text;
            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            IPAddress ip = IPAddress.Parse("172.16.20.237");
            int port = 26666;
            IPEndPoint remote = new IPEndPoint(ip, port);
            UdpClient udp = new UdpClient();
            udp.Connect(remote);
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            int sendLength = udp.Send(bytes, bytes.Length);
            SendResult.Text = "已向\t" + ip.ToString() + "\t发送\t" + sendLength + "\t字节。";
            chatContentText.AppendText("我:\n\t" + text + "\n");
            sendMsgText.Clear();
            udp.Close();
        }
    }
}

但是可以接受得到。

echo_lovely的主页 echo_lovely | 小虾三级 | 园豆:1579
提问于:2021-02-26 14:32
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册