HttpListenerCS客户端监听http
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; using System.Configuration; namespace MediaPlayerDemo20140925 { public partial class BVBMovieDemo : Form { bool loop = true;//是否重复播放 bool isStop = false; int currentMovieID = 0;//保存当前MovieID DataSet dsPlayItem = null;//当前 delegate object ControlMediaPlayer(object obj); DateTime? dtime; int state = 0; object objListerner;//销毁时使用 static string ip = ConfigurationManager.AppSettings["ip"];//http://*:8080/ public BVBMovieDemo() { InitializeComponent(); } private void BVBMovieDemo_Load(object sender, EventArgs e) { DataSet ds = BVBDBAccess.DBHelper.Query("select * from PlayItem where sortno=-1"); if (ds != null && ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; if (dt.Rows.Count > 0) { currentMovieID = (int)dt.Rows[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.URL = Application.StartupPath + dt.Rows[0]["URL"].ToString(); } else { MessageBox.Show("无启动视频,请在数据库中设置。","温馨提示"); return; } } Thread thread = new Thread(new ThreadStart(listern)); thread.Start(); timer1.Start(); this.Activate(); this.WindowState = FormWindowState.Maximized; } ///================================================================================================= /// <summary> Plays this object. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> ///================================================================================================= private bool Play() { ControlMediaPlayer op = delegate( object obj) { isStop = false; axWindowsMediaPlayer1.Ctlcontrols.play(); return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,""); } ///================================================================================================= /// <summary> Stops this object. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> ///================================================================================================= private bool Stop() { ControlMediaPlayer op = delegate(object obj){ isStop = true; axWindowsMediaPlayer1.Ctlcontrols.stop(); return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,""); } ///================================================================================================= /// <summary> Pauses this object. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> ///================================================================================================= private bool Pause() { ControlMediaPlayer op = delegate(object obj) { axWindowsMediaPlayer1.Ctlcontrols.pause(); return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,""); } ///================================================================================================= /// <summary> Resumes this object. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> ///================================================================================================= private bool Resume() { ControlMediaPlayer op = delegate(object obj) { isStop = false; axWindowsMediaPlayer1.Ctlcontrols.play(); return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,string.Empty); } ///================================================================================================= /// <summary> Previous this object. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> ///================================================================================================= private bool Previous() { ControlMediaPlayer op = delegate(object obj) { DataSet ds = BVBDBAccess.DBHelper.Query("select * from playitem"); if (ds != null && ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; DataRow[] drs = dt.Select("MovieID="+currentMovieID.ToString()); if (drs != null && drs.Length > 0) { DataRow[] drs2 = dt.Select("SortNo<"+drs[0]["SortNo"].ToString(),"sortno desc");//获取上一个movie if (drs2 != null && drs2.Length > 0) { if (drs2[0]["SortNo"].ToString() != "-1") { currentMovieID = (int)drs2[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.currentPlaylist.clear(); axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[0]["URL"].ToString(); axWindowsMediaPlayer1.Ctlcontrols.play(); } } } } axWindowsMediaPlayer1.Ctlcontrols.play(); return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,string.Empty); } private bool Next() { ControlMediaPlayer op = delegate(object obj) { DataSet ds = BVBDBAccess.DBHelper.Query("select * from playitem"); if (ds != null && ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; DataRow[] drs = dt.Select("MovieID=" + currentMovieID.ToString()); if (drs != null && drs.Length > 0) { DataRow[] drs2 = dt.Select("SortNo>" + drs[0]["SortNo"].ToString(), "sortno asc");//获取下一个movie if (drs2 != null && drs2.Length > 0) { currentMovieID = (int)drs2[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.currentPlaylist.clear(); axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[0]["URL"].ToString(); //axWindowsMediaPlayer1.fullScreen == true;// axWindowsMediaPlayer1.fullScreen; axWindowsMediaPlayer1.Ctlcontrols.play(); } } } return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op, string.Empty); } ///================================================================================================= /// <summary> 静音. </summary> /// <remarks> lidongbo, 2014/9/3. </remarks> ///================================================================================================= private bool MuteOn() { ControlMediaPlayer op = delegate(object obj) { axWindowsMediaPlayer1.settings.mute = true; return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,string.Empty); } ///================================================================================================= /// <summary> 取消静音. </summary> /// <remarks> lidongbo, 2014/9/3. </remarks> ///================================================================================================= private bool MuteOff() { ControlMediaPlayer op = delegate(object obj) { axWindowsMediaPlayer1.settings.mute = false; return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,string.Empty); } private int GetVolume() { ControlMediaPlayer op = delegate(object obj) { return axWindowsMediaPlayer1.settings.volume; }; return (int)axWindowsMediaPlayer1.Invoke(op,""); } private bool SetVolume(int volume) { ControlMediaPlayer op = delegate(object obj) { axWindowsMediaPlayer1.settings.volume = (int)obj; return true; }; return (bool)axWindowsMediaPlayer1.Invoke(op,volume); } private bool SetLoop(bool loop) { this.loop = loop; return true; //axWindowsMediaPlayer1.settings.setMode("loop", true); } ///================================================================================================= /// <summary> 获取当前进度. </summary> /// <remarks> lidongbo, 2014/9/26. </remarks> /// <returns> The seek. </returns> ///================================================================================================= private string GetSeek() { ControlMediaPlayer op = delegate(object obj) { return axWindowsMediaPlayer1.Ctlcontrols.currentPositionString; //return axWindowsMediaPlayer1.Ctlcontrols.currentPosition.ToString()+"|" +axWindowsMediaPlayer1.Ctlcontrols.currentPosition.ToString() + "|"+axWindowsMediaPlayer1.currentMedia.durationString + "|"+axWindowsMediaPlayer1.currentMedia.duration; }; return (string)axWindowsMediaPlayer1.Invoke(op,string.Empty); } private bool SetSeek(string position) { double seconds = 0; string[] arr = ((string)position).Split(':'); if (arr.Length == 0) { return false; } int iResult = 0; Array.Reverse(arr); for (int i = 0; i < arr.Length ; i++) { if (i == 0) { if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 60) { return false; } seconds += Convert.ToDouble(arr[i]); } else if (i == 1) { if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 60) { return false; } seconds += Convert.ToDouble(arr[i]) * 60; } else if (i == 2) { if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 24) { return false; } seconds += Convert.ToDouble(arr[i]) * 60 * 60; } } //if (arr.Length == 3) //{ // for (int i = arr.Length - 1; i >= 0; i--) // { // if (i == 0) // { // if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 60) // { // return false; // } // seconds += Convert.ToDouble(arr[i]); // } // else if (i == 1) // { // if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 60) // { // return false; // } // seconds += Convert.ToDouble(arr[i]) * 60; // } // else if (i == 2) // { // if (!int.TryParse(arr[i], out iResult) || iResult < 0 || iResult >= 24) // { // return false; // } // seconds += Convert.ToDouble(arr[i]) * 60 * 60; // } // } //} ControlMediaPlayer op = delegate(object obj) { string[] arr2 = axWindowsMediaPlayer1.currentMedia.durationString.Split(':'); double allsecends = 0; Array.Reverse(arr2); for (int i = 0; i < arr2.Length ; i++) { if (i == 0) { allsecends += Convert.ToDouble(arr2[i]); } else if (i == 1) { allsecends += Convert.ToDouble(arr2[i]) * 60; } else if (i == 2) { allsecends += Convert.ToDouble(arr2[i]) * 60 * 60; } } //for (int i = arr.Length - 1; i >= 0; i--) //{ // if (i == 0) // { // allsecends += Convert.ToDouble(arr2[i]); // } // else if (i == 1) // { // allsecends += Convert.ToDouble(arr2[i]) * 60; // } // else if (i == 2) // { // allsecends += Convert.ToDouble(arr2[i]) * 60 * 60; // } //} if ((double)obj > allsecends) { return false; } double result = (double)obj / allsecends * axWindowsMediaPlayer1.currentMedia.duration; axWindowsMediaPlayer1.Ctlcontrols.currentPosition = result; return true; }; if (!(bool)axWindowsMediaPlayer1.Invoke(op, seconds)) { return false; }; return true; } private object GetMovieInfo() { ControlMediaPlayer op = delegate(object obj) { return "当前视频ID:" + currentMovieID + ",名称:" + dsPlayItem.Tables[0].Select("MovieID="+currentMovieID)[0]["MovieName"].ToString(); }; return axWindowsMediaPlayer1.Invoke(op,""); } private bool PlayMovie(int movieid, ref string returnString) { ControlMediaPlayer op = delegate(object obj) { DataSet ds = BVBDBAccess.DBHelper.Query("select * from playitem"); if (ds != null && ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; DataRow[] drs = dt.Select("MovieID=" + movieid.ToString()); if (drs != null && drs.Length > 0) { currentMovieID = (int)drs[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.currentPlaylist.clear(); axWindowsMediaPlayer1.URL = Application.StartupPath + drs[0]["URL"].ToString(); axWindowsMediaPlayer1.Ctlcontrols.play(); return true; } } return false; }; if (!(bool)axWindowsMediaPlayer1.Invoke(op, string.Empty)) { returnString = "不存在"; return false; }; return true; } private void listern() { try { using (HttpListener listerner = new HttpListener()) { objListerner = listerner; listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问 listerner.Prefixes.Add(ip); listerner.Start(); while (true) { bool IsSuccess = false; string returnString = string.Empty; //等待请求连接 //没有请求则GetContext处于阻塞状态 HttpListenerContext ctx = listerner.GetContext(); ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 string operation = ctx.Request.QueryString["operation"]; string param = ctx.Request.QueryString["param"]; int iResult = 0; bool bResult = false; double dResult = 0; if (!string.IsNullOrEmpty(operation)) { switch (operation) { case "play": IsSuccess = Play(); break; case "stop": IsSuccess = Stop(); break; case "muteon": IsSuccess = MuteOn(); break; case "muteoff": IsSuccess = MuteOff(); break; case "setvolume": if (Int32.TryParse(param, out iResult) && iResult >= 0 && iResult <= 100) { SetVolume(Convert.ToInt32(param)); IsSuccess = true; } else { if (string.IsNullOrEmpty(param)) { returnString += "请输入参数"; } else { returnString += "参数的值应在0到100之间"; } IsSuccess = false; } break; case "getvolume": returnString = GetVolume().ToString(); IsSuccess = true; break; case "previous": IsSuccess = Previous(); break; case "next": IsSuccess = Next(); break; case "loopon": SetLoop(true); IsSuccess = true; break; case "loopoff": SetLoop(false); IsSuccess = true; break; case "pause": IsSuccess = Pause(); break; case "resume": IsSuccess = Resume(); break; case "getseek": returnString = GetSeek(); IsSuccess = true; break; case "setseek": IsSuccess = SetSeek(param); if (!IsSuccess) { returnString = "请输入正确的时间格式和时间点"; } break; case "currentmovie": returnString = GetMovieInfo().ToString(); IsSuccess = true; break; case "playmovie": if (Int32.TryParse(param, out iResult) && iResult > 0) { IsSuccess = PlayMovie(Convert.ToInt32(param), ref returnString); } else { IsSuccess = false; returnString += "请输入MovieID"; } break; } } //使用Writer输出http响应代码 using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { //writer.WriteLine("<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>The WebServer Test</title></head><body>"); //writer.Write(returnString); //writer.WriteLine("<form method=get action=/form>"); //writer.WriteLine("<input type=text name=operation value=''>"); //writer.WriteLine("<input type=text name=param value=''>"); //writer.WriteLine("</form>"); //writer.WriteLine("<input type=submit name=提交 value=提交>"); //writer.WriteLine("</body></html>"); ctx.Response.ContentType = "text/plain"; String callbackFunName = ctx.Request.QueryString["callbackparam"]; //writer.Write(callbackFunName + "([ { name:\"John\"}])"); writer.Write(callbackFunName + "({ result:\"" + (IsSuccess ? "success" : "fail") + "\",data:\"" + returnString + "\"})"); writer.Close(); ctx.Response.Close(); } } listerner.Stop(); } } catch { } //catch (Exception ex) { // MessageBox.Show(ex.Message); //} } private void timer1_Tick(object sender, EventArgs e) { if (loop && !isStop) { //利用影片总长度比较来得到 //axWindowsMediaPlayer1.Ctlcontrols.play(); if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsStopped) { DataSet ds = BVBDBAccess.DBHelper.Query("select * from playitem"); if (ds != null && ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; DataRow[] drs = dt.Select("MovieID=" + currentMovieID.ToString()); if (drs != null && drs.Length > 0) { DataRow[] drs2 = dt.Select("SortNo>" + drs[0]["SortNo"].ToString(), "sortno asc");//获取下一个movie if (drs2 != null && drs2.Length > 0) { currentMovieID = (int)drs2[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.currentPlaylist.clear(); axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[0]["URL"].ToString(); axWindowsMediaPlayer1.Ctlcontrols.play(); } else //到最后一个后播放第一个 { drs2 = dt.Select("SortNo>-1", "sortno asc");//获取播放第一个movie if (drs2 != null && drs2.Length > 0) { currentMovieID = (int)drs2[0]["MovieID"]; dsPlayItem = ds.Copy(); axWindowsMediaPlayer1.currentPlaylist.clear(); axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[0]["URL"].ToString(); axWindowsMediaPlayer1.Ctlcontrols.play(); } } } } } } } private void BVBMovieDemo_FormClosed(object sender, FormClosedEventArgs e) { if (objListerner != null) { ((HttpListener)objListerner).Abort(); } Application.Exit(); } private void BVBMovieDemo_MaximumSizeChanged(object sender, EventArgs e) { axWindowsMediaPlayer1.uiMode = "none"; } private void axWindowsMediaPlayer1_DoubleClickEvent(object sender, AxWMPLib._WMPOCXEvents_DoubleClickEvent e) { if (axWindowsMediaPlayer1.fullScreen) { axWindowsMediaPlayer1.fullScreen = false; } if (this.FormBorderStyle == FormBorderStyle.None) { this.FormBorderStyle = FormBorderStyle.FixedSingle; this.WindowState = FormWindowState.Normal; } else { this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; } } private void axWindowsMediaPlayer1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Escape && this.WindowState!= FormWindowState.Normal) { this.FormBorderStyle = FormBorderStyle.FixedSingle; this.WindowState = FormWindowState.Normal; } } private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e) { //if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPlaying) //{ // axWindowsMediaPlayer1.Ctlcontrols.pause(); //} //else if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPaused) //{ // axWindowsMediaPlayer1.Ctlcontrols.play(); //} } } }