连接到不同线程、同一进程上的 TcpListener

发布于 2024-10-05 03:18:54 字数 771 浏览 0 评论 0原文

我正在尝试对一些通信进行单元测试。使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

(り薆情海 2024-10-12 03:18:55

您使用了错误的 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 grab 127.0.0.1:1234. Use the TcpClient( String, int ) constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文