c# - 从客户端取消服务器套接字
问题描述
通过 .NET 异步套接字进行大型慢速馈送。数据来自仪器,因此可以是每秒 1 行(或更多)。有时它可能会停滞不前。
使用 MSDN 中的两个示例
asynchronous-client-socket-example
asynchronous-server-socket-example
我有来自套接字客户端的要求,停止从服务器中间流传输。每条消息都很小。不需要停止中间消息。需要能够停止循环 - 可以接收 1000 条小消息(发送给客户端)。
我的想法是保存引用client
并调用:
client.Shutdown(SocketShutdown.Both);
client.Close();
这是正确的方法吗?
private static Socket client;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com"); Dns.GetHostName()
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
//client = new Socket(ipAddress.AddressFamily,
// SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
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(e.ToString());
}
}
解决方案
推荐阅读
- excel - 根据单元格中的数字多次重复前一行的公式
- ruby-on-rails - 用should测试多个关联,应该属于使用外键
- amazon-ec2 - 无法通过用户数据命令将我现有的 EBS 卷(数据驱动器)附加到新启动的 EC2 实例 (RHEL 8)
- linux - 无法使用ffmpeg并排同步来自两个网络摄像头流的帧
- c++ - 分段错误:地址未映射/地址失败:(无)
- c# - 如何通过 include() 使用 ICollection 导航属性
- rest - (Django REST) API 设计:1 个带有多个查询参数的路径,还是多个路径?
- ruby-on-rails - 耙任务错误: JSON::ParserError: 765: unexpected token at '' 但在 Rails 控制台中工作正常
- javascript - 函数构造方法
- java - 为什么我不能在我的 Eclipse Maven 项目中将一个类导入到我的 java 文件中?