日期:2014-05-18 浏览次数:21072 次
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
namespace FilePlay
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
thListen = new Thread(new ThreadStart(listenConn)); //开始监听网络命令
thListen.Start();
}
private static HttpListener listener;
private static Thread thListen;
private static Thread thUpAudio=null;
HttpListenerResponse response = null;
HttpListenerRequest request = null;
private void listenConn()
{
CheckForIllegalCrossThreadCalls = false;
listener = new HttpListener();
listener.Prefixes.Add("http://*:9999/");
try
{
listener.Start();
while (true)
{
try
{
HttpListenerContext context = listener.GetContext();
request = context.Request;
response = context.Response;
try
{
if (thUpAudio != null)
{
thUpAudio.Abort();
}
}
catch { }
thUpAudio = new Thread(new ThreadStart(DoUpAudio)); //有新的播放请求就关掉旧的,建一个新的播放线程
thUpAudio.IsBackground = true;
thUpAudio.Start();
}
catch { }
}
}
catch {}
finally
{
listener.Close();
}
}
private void DoUpAudio()
{
try
{
string FILE_NAME = request.RawUrl;
FILE_NAME = @"D:\Audio\" + FILE_NAME; //这你要自己调试一下文件名对不对
if (!File.Exists(FILE_NAME)) { return; }
FileInfo fileinfo = new FileInfo(FILE_NAME);
int FILE_SIZE = (int)fileinfo.Length;
byte[] streambytes = new byte[FILE_SIZE];
FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
br.Read(streambytes, 0, FILE_SIZE);
response.ContentLength64 = streambytes.Length;
System.IO.Stream ws = response.OutputStream;
ws.Write(streambytes, 0, streambytes.Length);
br.Close();
fs.Close();
if (response != null)
response.Close();
}
catch { }
}
}
}