我正在尝试制作一个简单的C#网页服务器,目前您可以通过浏览器访问并只会显示“Hello World”。
我遇到的问题是,服务器可以正常接收数据 - 我可以获取浏览器的头部信息 - 但浏览器收不到我发送的任何内容。此外,我只能通过访问本地主机 (或 127.0.0.1) 来连接到服务器。我不能通过我的 IP 来连接它,也不是网络设置的问题,因为如果我运行 Apache,则可以正常工作。另外,我正在使用一个端口监控程序,在我尝试从浏览器连接之后,该进程的端口会停留在 TIME_WAIT 状态,即使我告诉连接关闭了,它应该回到 LISTEN。
这是相关的代码。有几个调用可能没有意义,但这是更大程序的一部分。
class ConnectionHandler
{
private Server server;
private TcpListener tcp;
private ArrayList connections;
private bool listening;
private Thread listeningThread;
public Server getServer()
{
return server;
}
private void log(String s, bool e)
{
server.log("Connection Manager: " + s, e);
}
private void threadedListen()
{
while (listening)
{
try
{
TcpClient t = tcp.AcceptTcpClient();
Connection conn = new Connection(this, t);
}
catch (NullReferenceException)
{
log("unable to accept connections!", true);
}
}
log("Stopped listening", false);
}
public void listen()
{
log("Listening for new connections", false);
tcp.Start();
listening = true;
if (listeningThread != null && listeningThread.IsAlive)
{
listeningThread.Abort();
}
listeningThread = new Thread(new ThreadStart(
this.threadedListen));
listeningThread.Start();
}
public void stop()
{
listening = false;
if (listeningThread != null)
{
listeningThread.Abort();
log("Forced stop", false);
}
log("Stopped listening", false);
}
public ConnectionHandler(Server server)
{
this.server = server;
tcp = new TcpListener(new IPEndPoint(
IPAddress.Parse("127.0.0.1"), 80));
connections = new ArrayList();
}
}
class Connection
{
private Socket socket;
private TcpClient tcp;
private ConnectionHandler ch;
public Connection(ConnectionHandler ch, TcpClient t)
{
try
{
this.ch = ch;
this.tcp = t;
ch.getServer().log("new tcp connection to "
+ this.tcp.Client.RemoteEndPoint.ToString(), false);
NetworkStream ns = t.GetStream();
String responseString;
Byte[] response;
Int32 bytes;
responseString = String.Empty;
response = new Byte[512];
bytes = ns.Read(response, 0, response.Length);
responseString =
System.Text.Encoding.ASCII.GetString(response, 0, bytes);
ch.getServer().log("Received: " + responseString);
String msg = "<html>Hello World</html>";
String fullMsg = "HTTP/1.x 200 OK
"
+ "Server: Test Server
"
+ "Content-Type: text/html; "
+ "charset=UTF-8
"
+ "Content-Length: " + msg.Length + "
"
+ "Date: Sun, 10 Aug 2008 22:59:59 GMT"
+ "
";
nsSend(fullMsg, ns);
nsSend(msg, ns);
ns.Close();
tcp.Close();
}
catch (ArgumentNullException e)
{
ch.getServer().log("connection error: argument null exception: " + e);
}
catch (SocketException e)
{
ch.getServer().log("connection error: socket exception: " + e);
}
}
private void nsSend(String s, NetworkStream ns)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(s);
ns.Write(data, 0, data.Length);
ns.Flush();
ch.getServer().log("Sent: " + s);
}
}
有人有任何想法吗?感觉好像是我自己的愚蠢,但我不知道是什么。我真的很感激任何的见解。