我遇到了一些问题,我无法在家检查它是否有效。
这是代码
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();
}
}
}
我也有一个简单的程序来连接到此程序,然后发送带有数据的字符串。它在本地主机上工作正常,但当我尝试连接另一台计算机时出现问题。
我什至关闭了我的电脑和路由器上的防火墙,就像我在朋友的笔记本电脑上所做的那样。每次我尝试连接时,他的计算机都拒绝连接。也许我做错了什么?
当然,ipAddress
现在是本地地址,因为目前仅使用该地址。有什么建议吗?
您需要将其设置为接受来自任何 IP 的连接,为此有一个 IPAddress 重载函数:
System.Net.IPAddress.Any
使用它而不是 127.0.0.1 它会解决你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)