c# - 套接字编程中提供了无效参数

标签 c# sockets udp udpclient

我想在 C# 中创建一个 UDP 客户端和服务器,当我运行它们时,在第一次发送和接收消息之后,这个错误就会实现。我的代码是:

byte[] barray = new byte[1024];
EndPoint ipre = new IPEndPoint(IPAddress.Any, 4040);
socketClint.Bind((IPEndPoint)ipre);
int rc = socketClint.ReceiveFrom(barray, ref ipre);

if (rc > 0)
{
    listBox1.Items.Add("Server: "+ BitConverter.ToInt32(barray,0));
}

这个错误大约是socketClint.Bind((IPEndPoint)ipre);线。

错误是:
System.Net.Sockets.SocketException was unhandled
HResult=-2147467259
Message=An invalid argument was supplied
Source=System
ErrorCode=10022
NativeErrorCode=10022
StackTrace:
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at client1.Form1.getmsg() in c:\Users\Inspiron 1545\Desktop\UDP\client1\client1\Form1.cs:line 38
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

内部异常:

最佳答案

Winsock 错误 10022 是 WSAEINVAL :

WSAEINVAL
10022

Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket — for instance, calling accept on a socket that is not listening.



在 Winsock bind() 的上下文中函数(Socket.Bind() 在内部使用),这意味着:

WSAEINVAL

An invalid argument was supplied.

This error is returned if the socket s is already bound to an address.



一旦套接字绑定(bind)到本地地址,就不能将其重新绑定(bind)到新的本地地址。你应该只绑定(bind)一次。

因此,在您的情况下,请调用 Bind()创建后socketClint只要。不要在每次调用 socketClint.ReceiveFrom() 之前调用它.

关于c# - 套接字编程中提供了无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441058/

相关文章:

c# - aspx中如何获取哪个页面抛出Application_error异常

c - c winsock编程中服务器收不到客户端消息

c - 使用 Scapy 与 C 套接字通信

javascript - 如何连接javascript和c#

c# - 在运行时替换 web.config appsettings 中的值(用于 Active Directory 身份验证)

c# - DVR 设备缺少 DirectShow GUID

c++ - recvfrom 在进入等待状态后只收到很少的数据包

c++ - 一台服务器多客户端 C/C++

c# - 有没有更好的方法来去除字符串中的空格和其他字符?

linux - udp 从驱动程序发送