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 = ;//保存当前MovieID
DataSet dsPlayItem = null;//当前
delegate object ControlMediaPlayer(object obj);
DateTime? dtime;
int state = ;
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 > )
{
DataTable dt = ds.Tables[];
if (dt.Rows.Count > )
{
currentMovieID = (int)dt.Rows[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.URL = Application.StartupPath + dt.Rows[]["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 > )
{
DataTable dt = ds.Tables[];
DataRow[] drs = dt.Select("MovieID="+currentMovieID.ToString());
if (drs != null && drs.Length > )
{
DataRow[] drs2 = dt.Select("SortNo<"+drs[]["SortNo"].ToString(),"sortno desc");//获取上一个movie
if (drs2 != null && drs2.Length > )
{
if (drs2[]["SortNo"].ToString() != "-1")
{
currentMovieID = (int)drs2[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.currentPlaylist.clear();
axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[]["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 > )
{
DataTable dt = ds.Tables[];
DataRow[] drs = dt.Select("MovieID=" + currentMovieID.ToString());
if (drs != null && drs.Length > )
{
DataRow[] drs2 = dt.Select("SortNo>" + drs[]["SortNo"].ToString(), "sortno asc");//获取下一个movie
if (drs2 != null && drs2.Length > )
{
currentMovieID = (int)drs2[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.currentPlaylist.clear();
axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[]["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 = ;
string[] arr = ((string)position).Split(':');
if (arr.Length == )
{
return false;
}
int iResult = ; Array.Reverse(arr);
for (int i = ; i < arr.Length ; i++)
{
if (i == )
{
if (!int.TryParse(arr[i], out iResult) || iResult < || iResult >= )
{
return false;
}
seconds += Convert.ToDouble(arr[i]);
}
else if (i == )
{
if (!int.TryParse(arr[i], out iResult) || iResult < || iResult >= )
{
return false;
}
seconds += Convert.ToDouble(arr[i]) * ;
}
else if (i == )
{
if (!int.TryParse(arr[i], out iResult) || iResult < || iResult >= )
{
return false;
}
seconds += Convert.ToDouble(arr[i]) * * ;
}
} //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 = ;
Array.Reverse(arr2);
for (int i = ; i < arr2.Length ; i++)
{
if (i == )
{
allsecends += Convert.ToDouble(arr2[i]);
}
else if (i == )
{
allsecends += Convert.ToDouble(arr2[i]) * ;
}
else if (i == )
{
allsecends += Convert.ToDouble(arr2[i]) * * ;
}
}
//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[].Select("MovieID="+currentMovieID)[]["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 > )
{
DataTable dt = ds.Tables[];
DataRow[] drs = dt.Select("MovieID=" + movieid.ToString());
if (drs != null && drs.Length > )
{
currentMovieID = (int)drs[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.currentPlaylist.clear();
axWindowsMediaPlayer1.URL = Application.StartupPath + drs[]["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 = ;//设置返回给客服端http状态代码
string operation = ctx.Request.QueryString["operation"];
string param = ctx.Request.QueryString["param"];
int iResult = ;
bool bResult = false;
double dResult = ;
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 >= && iResult <= )
{
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 > )
{
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 > )
{
DataTable dt = ds.Tables[];
DataRow[] drs = dt.Select("MovieID=" + currentMovieID.ToString());
if (drs != null && drs.Length > )
{
DataRow[] drs2 = dt.Select("SortNo>" + drs[]["SortNo"].ToString(), "sortno asc");//获取下一个movie
if (drs2 != null && drs2.Length > )
{
currentMovieID = (int)drs2[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.currentPlaylist.clear();
axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[]["URL"].ToString();
axWindowsMediaPlayer1.Ctlcontrols.play();
}
else //到最后一个后播放第一个
{
drs2 = dt.Select("SortNo>-1", "sortno asc");//获取播放第一个movie
if (drs2 != null && drs2.Length > )
{
currentMovieID = (int)drs2[]["MovieID"];
dsPlayItem = ds.Copy();
axWindowsMediaPlayer1.currentPlaylist.clear();
axWindowsMediaPlayer1.URL = Application.StartupPath + drs2[]["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();
//}
} }
}
HttpListenerCS客户端监听http的更多相关文章
- .Net客户端监听ZooKeeper节点数据变化
一个很简单的例子,用途是监听zookeeper中某个节点数据的变化,具体请参见代码中的注释 using System; using System.Collections.Generic; using ...
- 【Oracle】客户端监听配置
首先找到oracle软件安装的目录,找到\product\11.2.0\client_1\network\admin,打开tnsnames.ora文件: 粘贴一下内容: LISTENER= (DESC ...
- ZooKeeper监听机制
前言:Zookeeper的监听机制很多人都踩过坑,感觉实现了watcher 接口,后面节点的变化都会一一推送过来,然而并非如此. Watch机制官方声明:一个Watch事件是一个一次性的触发器,当被设 ...
- Spring boot实现监听Redis key失效事件实现和其它方式
需求: 处理订单过期自动取消,比如下单30分钟未支付自动更改订单状态 用户绑定隐私号码当订单结束取消绑定等 解决方案1: 可以利用redis自带的key自动过期机制,下单时将订单id写入redis,过 ...
- ZooKeeper(二):多个端口监听的建立逻辑解析
ZooKeeper 作为优秀的分布系统协调组件,值得一探究竟.它的启动类主要为: 1. 单机版的zk 使用 ZooKeeperServerMain 2. 集群版的zk 使用 QuorumPeerMai ...
- java实现服务端守护进程来监听客户端通过上传json文件写数据到hbase中
1.项目介绍: 由于大数据部门涉及到其他部门将数据传到数据中心,大部分公司采用的方式是用json文件的方式传输,因此就需要编写服务端和客户端的小程序了.而我主要实现服务端的代码,也有相应的客户端的测试 ...
- Socket(TCP)客户端请求和服务端监听和链接基础(附例子)
一:基础知识回顾 一: Socket 类 实现 Berkeley 套接字接口. Socket(AddressFamily, SocketType,ProtocolType) 使用指定的地址族.套接字类 ...
- 安卓作为udp服务器,PC作为客户端,仅监听
安卓客户端作为udp服务器,监听其他客户端的数据,测试已成功 本次实验所用数据: 安卓作为服务器: 端口:8888 IP:192.168.1.104 电脑作为客户端: 端口:50 ...
- Zookeeper 客户端API调用示例(基本使用,增删改查znode数据,监听znode,其它案例,其它网络参考资料)
9.1 基本使用 org.apache.zookeeper.Zookeeper是客户端入口主类,负责建立与server的会话 它提供以下几类主要方法 : 功能 描述 create 在本地目录树中创建 ...
随机推荐
- We are doomed, and RPC does not help
第一种死法:Big ball of Mud 架构里最常用的反面案例是 big ball of mud.很大程度上可以说打格子,把复杂的系统拆解成小格子是架构师最重要的工作.这个小格子有很多种名字,比如 ...
- 最新 Windows 10 应用项目模板发布
以下是最新的Visual Studio 2015 Windows 10 应用程序模板. Windows 10中几乎所有的官方应用都遵循这样一个设计模板:在左上方有一个所谓的导航栏.点击该导航按钮,左侧 ...
- javax.persistence.PersistenceException: No Persistence provider for EntityManager named ...
控制台下输出信息 原因:persistence.xml必须放在src下META-INF里面. 若误放在其他路径,就会迷路.
- Atitit.提升稳定性-----分析内存泄漏PermGen OOM跟解决之道...java
Atitit.提升稳定性-----分析内存泄漏PermGen OOM跟解决之道...java 1. 内存区域的划分 1 2. PermGen内存溢出深入分析 1 3. PermGen OOM原因总结 ...
- paip.java 调用c++ dll so总结
paip.java 调用c++ dll so总结 ///////JNA (这个ms sun 的) 我目前正做着一个相关的项目,说白了JNA就是JNI的替代品,以前用JNI需要编译一层中间库,现在JNA ...
- Leetcode 345 Reverse Vowels of a String 字符串处理
题意:倒置字符串中的元音字母. 用两个下标分别指向前后两个相对的元音字母,然后交换. 注意:元音字母是aeiouAEIOU. class Solution { public: bool isVowel ...
- 如何编写一个PHP的C扩展
为什么要用C扩展 C是静态编译的,执行效率比PHP代码高很多.同样的运算代码,使用C来开发,性能会比PHP要提升数百倍.IO操作如CURL,因为耗时主要在IOWait上,C扩展没有明显优势. 另外C扩 ...
- Scala access modifiers and qualifiers in detail
来自:http://www.jesperdj.com/2016/01/08/scala-access-modifiers-and-qualifiers-in-detail/ Just like Jav ...
- [转]Java Spring的Ioc控制反转Java反射原理
转自:http://www.kokojia.com/article/12598.html 学习一个东西的时候,如果想弄明白,最好想想框架内部是如何实现的,如果是我做我会怎么实现.下面我就写一个Ioc ...
- 【linux】文件隐藏属性
这些隐藏的属性确实对于系统有很大的帮助的- 尤其是在系统安全 (Security) 上面,重要的紧呢!不过要先强调的是,底下的chattr指令只能在Ext2/Ext3的文件系统上面生效, 其他 ...