我一直在尝试用 C# 制作一个简单的 udp 聊天应用程序。一个小时前它还在工作,但我并没有完全意识到它发生了什么,或者我到底做了什么改变。当我尝试侦听任何传入消息时,我只是得到一个异常说“提供了无效参数”,指向变量'rcv'。这是代码:
public partial class Form1 : Form
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),
1234);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(send));
thread1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(new ThreadStart(receive));
thread2.Start();
}
private void receive()
{
while (true)
{
byte[] rcv = new byte[2048];
int size = sock.Receive(rcv); // this is where the exception is, pointing at rcv.
char[] chars = new char[size];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int length = d.GetChars(rcv, 0, size, chars, 0);
System.String recv = new System.String(chars);
textBox1.Text += recv.ToString();
}
}
private void send()
{
byte[] msg = Encoding.UTF8.GetBytes(textBox1.Text);
sock.SendTo(msg, localEndPoint);
}
private void button3_Click(object sender, EventArgs e)
{
sock.Close();
}
}
老实说,我在使用套接字时从未见过这个异常。我想也许套接字已打开并正在使用中,所以我尝试关闭它但没有成功。任何提示将不胜感激。