我正在为通过互联网连接到它的多个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图片。认为它可能会有所帮助。
答案 0 :(得分:0)
我遇到过类似的问题。
http://81.62.12.32/
并打开http://81.62.126.41:9000/
,您会看到两个不同的错误。 结论:问题不在您的代码中。它位于您的Web服务器设置或防火墙设置中。