加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法从远程计算机连接

发布时间:2020-12-15 04:08:09 所属栏目:百科 来源:网络整理
导读:我有一些问题,我不能在家检查它是否工作. 这是代码 using System;using System.Net;using System.Net.Sockets;using System.Threading;using System.IO;using System.Net.Security;class Program{ private static IPAddress ipAddress = IPAddress.Parse("12
我有一些问题,我不能在家检查它是否工作.
这是代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net.Security;

class Program
{
    private static IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    private static int port = 6000;
    private static string data = null;

    static void Main(string[] args)
    {
        Thread thread = new Thread(new ThreadStart(receiveThread));
        thread.Start();
        Console.ReadKey();
    }

    public static void receiveThread()
    {
        while (true)
        {
            TcpListener tcpListener = new TcpListener(ipAddress,port);
            tcpListener.Start();

            Console.WriteLine("Waiting for connection...");

            TcpClient tcpClient = tcpListener.AcceptTcpClient();

            Console.WriteLine("Connected with {0}",tcpClient.Client.RemoteEndPoint);

            while (!(tcpClient.Client.Poll(20,SelectMode.SelectRead)))
            {
                NetworkStream networkStream = tcpClient.GetStream();
                StreamReader streamReader = new StreamReader(networkStream);

                data = streamReader.ReadLine();

                if(data != null)
                    Console.WriteLine("Received message: {0}",data);
            }
            Console.WriteLine("Dissconnected...n");
            tcpListener.Stop();
        }
    }
}

我有一个简单的程序连接到这个,然后发送一个包含数据的字符串.它在localhost上工作正常,但是当我尝试连接不同的计算机时出现问题.

我甚至关闭了我的PC和路由器上的防火墙,就像我在朋友的笔记本电脑上做的那样.每次我尝试连接时,他的计算机都拒绝连接.也许我做错了什么?

当然,ipAddress现在是一个本地地址,因为它目前只与它一起工作.有什么建议吗?

解决方法

你需要将它设置为接受来自任何IP的连接,有一个IPAddress重载函数:
System.Net.IPAddress.Any

使用它代替127.0.0.1,它将解决您的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读