TcpListener-无法建立连接,因为目标计算机主动拒绝了它 [英] TcpListener - No connection could be made because the target machine actively refused it

查看:70
本文介绍了TcpListener-无法建立连接,因为目标计算机主动拒绝了它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        int port = 44344;

        var thread = new Thread(
            () =>
            {
                TcpListener listener = null;
                try
                {
                    listener = new TcpListener(IPAddress.Any, port);
                    listener.Start();

                    while (true)
                    {
                        var client = listener.AcceptTcpClient();
                    }
                }
                catch (ThreadInterruptedException)
                { }

                if (listener != null)
                    listener.Stop();
            });
        thread.Start();

        Thread.Sleep(TimeSpan.FromSeconds(1));

        var socket = new Socket(SocketType.Stream, ProtocolType.IP);
        socket.Connect("localhost", port);

在我的PC上运行时,此代码在最后一行失败,并带有由于目标计算机主动拒绝连接而无法建立连接"异常.有什么想法是什么原因以及如何解决?

This code fails on the last line with "No connection could be made because the target machine actively refused it" exception, when running on my PC. Any ideas what can be the reason and how to fix it?

推荐答案

解决方案是使用指定的AddressFamily参数创建客户端套接字:

The solution was to create the client socket with an AddressFamily parameter specified:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

这篇关于TcpListener-无法建立连接,因为目标计算机主动拒绝了它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆