c# - 如何在 c# 上使用异步连接通过套接字发送多条消息
问题描述
我正在尝试将 Microsoft 示例代码用于:
和“异步客户端套接字” https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example
我正在尝试做的是调整客户端应用程序并使其能够在不关闭客户端应用程序的情况下向服务器发送多条消息。我正在尝试无限测试循环,但是当我发送第二条消息时,我收到了错误:
public void connect()
{
while (true)
{
// Conectarse a un dispositivo remoto
try
{
// Establish the remote endpoint for the socket
IPEndPoint direccion = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 45000);
// Create a TCP/IP socket.
Socket client = new Socket(direccion.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(direccion, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Console.WriteLine("Write your message bellow");
String data_s = Console.ReadLine();
Send(client, data_s);
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Aqui esta el error");
Console.WriteLine(e.ToString());
}
}
}
应该注意的是,我在套接字编程方面没有太多经验,所以我不确定 connect 方法是否是进入和解决问题的正确位置。服务器应用程序和客户端应用程序的其余代码是相同的,我只更改了连接方法和一些验证,这应该不是问题。
我试着只循环这个代码块:
// Send test data to the remote device.
Console.WriteLine("Write your message bellow");
String data_s = Console.ReadLine();
Send(client, data_s);
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
但我得到了:
解决方案
推荐阅读
- php - SilverStripe 4 自定义错误页面未显示
- node.js - Cannot destructure propery error - googleapi
- regex - 正则表达式:从双引号中提取值
- magento - Magento 1.9:观察者不工作。有什么方法可以测试观察者是否工作?
- angular - Angular/Ionic 模块中对 ModalController 的依赖导致服务“无法解析所有参数”
- java - Combine multiple `Collectors::groupBy` functions with Java Streams
- python - 如何将数据框写入excel并更改格式
- java - application slowness on specific version of jdk
- java - Caused by: java.net.NoRouteToHostException: Cannot assign requested address (Address not available)
- css - 具有固定标题的引导表 - Angular 5