我正在使用此类从/向我的应用程序发送 Echo 测试
public class SocketClient
{
Socket socket = null;
static ManualResetEvent clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
public SocketClient()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
public string Send(string serverName, int portNumber, string data)
{
string response = "Timeout";
if (socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(serverName, portNumber);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
response = e.SocketError.ToString();
clientDone.Set();
});
byte[] payload = Encoding.UTF8.GetBytes(data);
socketEventArg.SetBuffer(payload, 0, payload.Length);
clientDone.Reset();
socket.SendToAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "not initialized";
}
return response;
}
public string Recieve(int portNumber)
{
string response = "Timeout";
if (socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
clientDone.Set();
});
socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
clientDone.Reset();
socket.ReceiveFromAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
return response;
}
public void Close()
{
socket.Close();
}
}
这是我如何使用它:
SocketClient client = new SocketClient();
client.Send("192.168.1.2",77 , "besm ellah");
textBox1.Text=client.Recieve(77);
它总是通过参数异常在
socket.SendToAsync(socketEventArg);
处未处理“参数 remoteEP 不能是 DnsEndPoint 类型。”
“参数名称:remoteEP”
我在 windows 功能上启用了简单 TCP/IP 的功能,但它也不起作用。
-UPDATE-
我尝试将代码更改为:
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
socketEventArg.RemoteEndPoint = new IPEndPoint(localIPs[3], portNumber);
它没有给出异常,但消息没有通过。
最佳答案
好吧,看起来您应该将其更改为不同类型的端点,而不是 DNS 端点。
我认为您应该使用 IPEndPoint
http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx