gpt4 book ai didi

c# - 套接字通信C#

转载 作者:行者123 更新时间:2023-11-30 12:50:55 25 4
gpt4 key购买 nike

我正在使用此类从/向我的应用程序发送 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 功能,但它也不起作用。

-更新-

我尝试将代码更改为:

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

关于c# - 套接字通信C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com