我想在 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
10022Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to thesetsockopt
function). In some instances, it also refers to the current state of the socket — for instance, callingaccept
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/