【发布时间】:2016-12-18 23:09:03
【问题描述】:
我正在尝试在此处编写 MSDN 示例的非常简单(对我来说似乎是这样)扩展:https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx
客户端会循环运行。在下面的例子中,我每次都在重新初始化客户端。
while (true)
{
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
string myCommand = "";
Console.WriteLine("Enter command:");
myCommand = Console.ReadLine();
if (myCommand == "quit") break;
// Send test data to the remote device.
Send(client, myCommand + "<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();
}
它不能始终如一地工作,我经常收到错误“无法访问已处置的对象”,但无法弄清楚是什么触发了它。 我是套接字编程和多线程的初学者。
【问题讨论】:
-
尝试将代码包装在 Using 语句中,以确保正确处理所有内容。
-
查看控制台,当我得到错误时,这些行被乱序打印:
-
Socket 连接到 192.168.56.1:11000 输入命令:test 向服务器发送了 9 个字节。收到的响应:无法识别的命令
输入命令:套接字连接到 192.168.56.1:11000 -
我将所有内容都放在了 using 语句的 while 循环中,但仍然出现相同的错误。
-
我知道它有点钓鱼,但您可能还希望将代码放入单独的异步任务函数中,并在每次等待时调用它。我不能保证它会起作用,但它会防止任何资源冲突。
标签: c# multithreading sockets tcp