using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace MyThread
{
class FileServer
{
private String root;
private Thread listenerThread;
private void worker(object state)
{
TcpClient client = state as TcpClient;
try
{
client.ReceiveTimeout = 2000;
Stream stream = client.GetStream();
System.IO.StreamReader sr = new StreamReader(stream);
String line = sr.ReadLine();
String[] array = line.Split(‘ ‘);
String path = array[1].Replace(‘/‘, ‘\\‘);
String filename = root + path;
if (File.Exists(filename)) // 如果下载文件存在,开始下载这个文件
{
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read,
FileShare.Read);
byte[] buffer = new byte[8192]; // 每次下载8K
int count = 0;
String responseHeader = "HTTP/1.1 200 OK\r\n" +
"Content-Type:application/octet-stream\r\n" +
"Content-Disposition:attachment;filename=" +
filename.Substring(filename.LastIndexOf("\\") + 1) + "\r\n\r\n";
byte[] header = ASCIIEncoding.ASCII.GetBytes(responseHeader);
stream.Write(header, 0, header.Length);
while ((count = fileStream.Read(buffer, 0, buffer.Count())) > 0)
{
stream.Write(buffer, 0, count);
}
Console.WriteLine(filename + "下载完成");
}
else // 文件不存在,输出提示信息
{
String response = "HTTP/1.1 200 OK\r\nContent-Type:text/plain;charset=utf-8\r\n\r\n文件不存在";
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(response);
stream.Write(buffer, 0, buffer.Length);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (client != null)
{
client.Close();
}
}
}
private void listener()
{
TcpListener listener = new TcpListener(1234);
listener.Start(); // 开始监听客户端请求
TcpClient client = null;
while (true)
{
client = listener.AcceptTcpClient();
client.ReceiveTimeout =2000;
ThreadPool.QueueUserWorkItem(worker, client); // 从线程池中获得一个线程来处理客户端请求
}
}
public FileServer(String root)
{
this.root= root;
}
public void start()
{
listenerThread = new Thread(listener);
listenerThread.Start(); // 开始运行监听线程
}
}
}
C#线程系列讲座(3):线程池和文件下载服务器
标签:
原文地址:http://www.cnblogs.com/qixuejia/p/4288305.html