我正在为通过 Internet 连接到它的多个 winform 客户端创建一个小型服务器。以下代码在设置为本地地址时有效:
服务器:
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(9000);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
Winform客户端:
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 9000);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
}
这些代码可以很好地通过网络相互交谈。但是当我决定改变这行代码时
clientSocket.Connect("127.0.0.1", 9000);
至
clientSocket.Connect("81.62.126.41", 9000);
对于我的 ip 地址,它给了我以下 SocketException:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
所以我尝试了一些事情。端口转发端口 9000,因为我在路由器后面。为端口 9000 创建入站和出站规则。我在服务器运行时访问了http://www.canyouseeme.org/,该网站实际上可以看到我的服务。
有谁知道我能做些什么来解决这个问题?
这是服务器运行时 netstat 的图片。认为它可能会有所帮助。