我在c#中运行TCP服务器。该程序似乎运行并保持新客户端(它停在TcpClient客户端= this.tcpListener.AcceptTcpClient();)等待新连接。但是,如果我检查网络(使用netstat命令),服务器没有监听,这意味着没有运行。我也试过不同的端口,但我想比端口80应该适合测试(我也试过其他端口,但没有一个工作)。我的代码有什么问题?也许OS正在阻止服务器?
namespace TCPServer
{
class TestClass
{
static void Main(string[] args)
{
Server TCPServer = new Server();
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
System.Console.WriteLine("Server started");
}
//starts the tcp listener and accept connections
private void ListenForClients()
{
this.tcpListener.Start();
System.Console.WriteLine("Listener started");
while (true)
{
System.Console.WriteLine("Accepting Clients");
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
System.Console.WriteLine("Client connected");
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
//Read the data from the client
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client; //start the client
NetworkStream clientStream = tcpClient.GetStream(); //get the stream of data for network access
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0) //if we receive 0 bytes
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
//Reply
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
}
}
}
更新 我配置应用程序以获得防火墙豁免。我在windows7中运行。我还检查了端口3000,没有收听该端口。我使用netstat输出来确定它是否正在收听。