110,533
社区成员
发帖
与我相关
我的任务
分享
我自己实现一个简单的HTTP服务器,其中处理发送文件内容时,
浏览器接收到的数据只是其中一部分,下面的我的处理代码
class httpprocessor
{
private Socket s;
private StreamReader sr;
private string method;
private string url;
private string protocol;
private Hashtable hashtable;
public httpprocessor( ref Socket s)
{
this.s = s;
hashtable = new Hashtable();
}
public void process()
{
try
{
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite);
sr = new StreamReader(ns);
parserequest();
readheaders();
writeurl();
s.Shutdown(SocketShutdown.Both);
s.Close();
}
catch (Exception e)
{
LogTools.write(e);
}
}
public void parserequest()
{
string request = sr.ReadLine();
LogTools.write(request);
string[] tokens = request.Split(' ');
method = tokens[0];
url = tokens[1];
int index = url.IndexOf('?');
if (index != -1)
{
url = url.Substring(0, index);
}
protocol = tokens[2];
}
public void readheaders()
{
string line;
while ((line = sr.ReadLine()) != null && line != "")
{
LogTools.write(line);
string[] tokens = line.Split(':');
string name = tokens[0];
string value = "";
for (int i = 1; i < tokens.Length; i++)
{
value += tokens[i];
if (i < tokens.Length - 1) tokens[i] += ":";
}
hashtable[name] = value;
}
}
public void writeurl()
{
try
{
string id = url.Substring(1);
ProofInfo p = LocalHttpServer.ProofPackagePanel.getProofInfoById(id);
if (p == null)
{
writefailure();
return;
}
FileInfo file = new FileInfo(p.Prf_Path);
//这里发送文件,但有些文件只能收到一部分,有些文件又能全部接收。
s.SendFile(file.FullName, writesuccess(file.Length), null, TransmitFileOptions.WriteBehind);
}
catch (FileNotFoundException e)
{
writefailure();
LogTools.write(e);
}
catch (IOException e)
{
LogTools.write(e);
}
}
public byte[] writesuccess(long len)
{
string str = "";
str += "http/1.0 200 ok\r\n";
str += "Server: LocalHttpServer\r\n";
str += "Cache-Control: max-age=31104000\r\n";
str += "Content-Type: image/jpeg\r\n";
str += "Accept-Ranges: bytes\r\n";
str += "Content-Length: " + len + "\r\n\r\n";
byte[] data = Encoding.ASCII.GetBytes(str);
return data;
}
public void writefailure()
{
string str = "";
str += "http/1.0 404 file not found\r\n";
str += "connection: close\r\n";
byte[] data = Encoding.ASCII.GetBytes(str);
s.Send(data);
}
}
//这里发送文件,但有些文件只能收到一部分,有些文件又能全部接收。
s.SendFile(file.FullName, writesuccess(file.Length), null, TransmitFileOptions.WriteBehind);