多年来,我一直在寻找解决这个问题的方法。我尝试了很多东西,包括 BeginReceive(),但都无济于事。必须有办法做到这一点,使 UDP-Client 接收非阻塞和线程安全的调用。我正在尝试接收消息并将其写入富文本框。
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;
using System.IO;
namespace Chat
{
public partial class Form1 : Form
{
public bool contfunctioning = true; public bool changedsplay = false;
public string enteredchats, msg, chatstring, Chats;
UdpClient subscriber = new UdpClient(8899);
UdpClient publisher = new UdpClient("230.0.0.100", 8898);
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
string ConnectIPAddress;
ConnectIPAddress = txtboxIP.Text;
IPAddress addr = IPAddress.Parse(ConnectIPAddress);
MessageBox.Show("Subscribing to chat server on " + ConnectIPAddress + ".", ConnectIPAddress);
EndPoint ep = null;
// This is where The UDPClient subscriber needs to Begin.Receive()
}
private void btnSend_Click(object sender, EventArgs e)
{
enteredchats = txtboxUsr.Text + " " + txtboxentertxt.Text;
txtboxentertxt.Clear();
msg = String.Format(enteredchats);
sdata = Encoding.ASCII.GetBytes(msg);
publisher.Send(sdata, sdata.Length);
}
}
}
足够的代码,是吗?提前感谢所有回复。