连接到不同线程、同一进程上的 TcpListener
我正在尝试对一些通信进行单元测试。使用 C# 编写 TCP 代码。我创建了一个支持 TcpListener 的快速线程。每次 TcpClient 尝试连接时,我都会收到“通常只允许每个套接字地址(协议/网络地址/端口)仅使用一次”异常。您不能在同一进程中托管并连接到同一端口吗?
[Test]
public void Foo()
{
Thread listenerThread = new Thread(TcpListenerThread);
listenerThread.Start();
Thread.Sleep(5000);
TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Loopback, 1234));
}
private void TcpListenerThread()
{
TcpListener listener = new TcpListener(IPAddress.Any, 1234);
listener.Start();
TcpClient socket = listener.AcceptTcpClient();
StreamWriter writer = new StreamWriter(socket.GetStream());
writer.Write(File.ReadAllBytes("../../random file.txt"));
}
I'm trying to unit test some comm. code over TCP in C#. I've created a quick thread that stands up a TcpListener. Each time the TcpClient tries to connect I get an "Only one usage of each socket address (protocol/network address/port) is normally permitted" exception. Can you not host on and connect to the same port in the same process?
[Test]
public void Foo()
{
Thread listenerThread = new Thread(TcpListenerThread);
listenerThread.Start();
Thread.Sleep(5000);
TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Loopback, 1234));
}
private void TcpListenerThread()
{
TcpListener listener = new TcpListener(IPAddress.Any, 1234);
listener.Start();
TcpClient socket = listener.AcceptTcpClient();
StreamWriter writer = new StreamWriter(socket.GetStream());
writer.Write(File.ReadAllBytes("../../random file.txt"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用了错误的
TcpClient 构造函数
- 这会将客户端绑定到本地地址和端口,因此最终侦听器和客户端都会尝试获取127.0.0.1:1234< /代码>。使用
TcpClient( String, int )
构造函数。You are using wrong constructor of the
TcpClient
- this one binds the client to local address and port, so you end up with both the listener and the client trying to grab127.0.0.1:1234
. Use theTcpClient( String, int )
constructor.