今天使用wcf的duplex方式实现了视频对话,但是很卡,晚上准备改写为Socket方式或者将客户端定时请求服务器资源改变为服务器主动回调客户端取资源。简要将今天的尝试记录一下。
思路是文本聊天通过duplex方式进行,而视频部分则通过客户端定时将截屏发送到服务器,再由服务器转发到聊天对象。
编写WCF服务端定义服务契约:
代码 [ServiceContract(CallbackContract = typeof (IChatServiceCallBack))]public interface IChatService
{
[OperationContract]
bool Login( string user, string partner);
[OperationContract]
bool SendMessage(MessageInfo message);
[OperationContract]
List < UserVIDeo > GetVIDeosByte( string username, string partnername);
[OperationContract]
voID SendVIDeoByte(UserVIDeo vIDeo);
}
[ServiceContract]
public interface IChatServiceCallBack
{
[OperationContract(IsOneWay = true )]
voID Receive(List < MessageInfo > messages);
}
实现服务:
代码 public class UserUpdate // 记录用户上次取消息的时间
{
public string Username{ get ; set ;}
public DateTime LatestTime{ get ; set ;}
}
public class ChatService : IChatService
{
IChatServiceCallBack callBack;
Timer timer;
string _user;
string _partner;
public static List < UserUpdate > ListUserUpdate = new List < UserUpdate > (); // 存放用户取得消息的最近时间
public static List < MessageInfo > ListMessages = new List < MessageInfo > (); // 模拟存放聊天信息
public static List < UserVIDeo > ListVIDeos = new List < UserVIDeo > (); // 临时存放视频信息
public voID StartTimer()
{
timer = new Timer( new TimerCallback(CallClIEntToReceiveMsg), null , 500 , 500 ); // 定时回调客户端,传送资源
}
public bool Login( string user, string partner)
{
try
{
_user = user;
_partner = partner;
if (ListUserUpdate.Where(m => m.Username == user).ToList().Count == 0 )
{
ListUserUpdate.Add( new UserUpdate() { Username = user, LatestTime = DateTime.Now });
}
callBack = OperationContext.Current.GetCallbackChannel < IChatServiceCallBack > ();
StartTimer();
return true ;
}
catch
{
return false ;
}
}
private voID CallClIEntToReceiveMsg( object o) // 客户端回调完成后
{
try
{
DateTime dt = ListUserUpdate.Where(m => m.Username == _user).ToList()[ 0 ].LatestTime;
ListUserUpdate.Remove(ListUserUpdate.Where(m => m.Username == _user).ToList()[ 0 ]);
ListUserUpdate.Add( new UserUpdate() { Username = _user, LatestTime = DateTime.Now });
callBack.Receive(ListMessages.Where(m => (m.Sender == _user && m.ReceiveUser == _partner && m.SendTime > dt) || (m.ReceiveUser == _user && m.Sender == _partner && m.SendTime > dt)).ToList());
}
catch
{
timer.dispose();
StartTimer();
}
}
public bool SendMessage(MessageInfo message) // 发送消息方法
{
try
{
ListMessages.Add(message);
return true ;
}
catch
{
return false ;
}
}
public List < UserVIDeo > GetVIDeosByte( string username, string partnername) // 取得视频信息
{
List < UserVIDeo > List = new List < UserVIDeo > ();
List = ListVIDeos.Where(m => (m.Username == partnername && m.Partnername == username)).ToList();
if (List.Count > 0 )
{
ListVIDeos.RemoveAll(m => (m.Username == partnername && m.Partnername == username));
}
return List;
}
public voID SendVIDeoByte(UserVIDeo vIDeo)
{
ListVIDeos.Add(vIDeo);
}
}
消息契约和用户视频对象
代码 [DataContract]public class MessageInfo
{
[DataMember]
public string ID { set ; get ; }
[DataMember]
public string Title { set ; get ; }
[DataMember]
public string Message { set ; get ; }
[DataMember]
public DateTime SendTime { set ; get ; }
[DataMember]
public DateTime ? ReadTime { set ; get ; }
[DataMember]
public string Sender { set ; get ; }
[DataMember]
public string ReceiveUser { set ; get ; }
[DataMember]
public string ReceiveOrgan { set ; get ; }
[DataMember]
public string ReceiveMode { set ; get ; }
[DataMember]
public int State { set ; get ; }
[DataMember]
public int Receipt { set ; get ; }
[DataMember]
public string Source { set ; get ; }
}
[DataContract]
public class UserVIDeo
{
[DataMember]
public string Username { get ; set ; }
[DataMember]
public string Partnername { set ; get ; }
[DataMember]
public byte [] VIDeoByte { set ; get ; }
}
Silverlight客户端代码
首先需要登录服务器,使服务器开始监控消息
代码 address = new EndpointAddress( " http://localhost:8752/ChatService.svc%22);binding = new PollingDuplexhttpBinding(PollingDuplexMode.MultipleMessagesPerPoll);
proxy = new ChatServiceClIEnt(binding, address);
proxy.ReceiveReceived += new EventHandler < ReceiveReceivedEventArgs > (proxy_ReceiveReceived);
proxy.LoginCompleted += new EventHandler < LoginCompletedEventArgs > (proxy_LoginCompleted);
proxy.LoginAsync(User, Partner);
当链接到服务器之后呢,就开始监控对方视频资源,当然这里可以做成邀请-同意的模式另外触发这个事件 voID proxy_LoginCompleted( object sender, LoginCompletedEventArgs e)
{
AddText( " connected " );
// 连接到服务器后开始接收视频
ReceiveVIDeo();
}
当连接到服务器之后,一旦服务器收到对方发给自己的信息就可以执行回调 *** 作
代码 voID proxy_ReceiveReceived( object sender, ReceiveReceivedEventArgs e){
if (e.Error == null )
{
foreach (MessageInfo msg in e.messages)
{
AddText(msg.Sender + " say: " + msg.Message);
}
}
}
这里采用的方式比较简单,就是有客户端定时去服务器上取得数据。
代码 voID ReceiveVIDeo(){
System.windows.Threading.dispatcherTimer timerForReceive = new System.windows.Threading.dispatcherTimer();
timerForReceive.Interval = new TimeSpan( 0 , 0 , 200 );
timerForReceive.Tick += new EventHandler(timerForReceive_Tick);
timerForReceive.Start();
AddText( " start to receive vIDeo " );
}
voID timerForReceive_Tick( object sender, EventArgs e)
{
proxy.GetVIDeosByteCompleted += new EventHandler < GetVIDeosByteCompletedEventArgs > (proxy_GetVIDeosByteCompleted);
proxy.GetVIDeosByteAsync(User, Partner);
}
voID proxy_GetVIDeosByteCompleted( object sender, GetVIDeosByteCompletedEventArgs e)
{
if (e.Error == null )
{
foreach (ChatService.UserVIDeo vIDeo in e.Result)
{
MemoryStream ms = new MemoryStream(vIDeo.VIDeoByte);
BitmAPImage bitmap = new BitmAPImage();
bitmap.SetSource(ms);
imagePartner.source = bitmap;
ms.Close();
}
}
}
而向服务器传递数据也是通过定时截图发送的方式进行
代码 voID btnSendVIDeo_Click( object sender, RoutedEventArgs e){
System.windows.Threading.dispatcherTimer timer = new System.windows.Threading.dispatcherTimer();
timer.Interval = new TimeSpan( 0 , 0 , 200 );
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
AddText( " start sending vIDeo " );
}
此方法为向服务器发送视频比特流
代码 voID timer_Tick( object sender, EventArgs e){
WriteableBitmap bmp = new WriteableBitmap( this .rectangleUser, null );
MemoryStream ms = new MemoryStream();
EncodeJpeg(bmp, ms);
UserVIDeo userVIDeo = new UserVIDeo();
userVIDeo.Partnername = this .Partner;
userVIDeo.Username = this .User;
userVIDeo.VIDeoByte = ms.GetBuffer();
proxy.SendVIDeoByteAsync(userVIDeo);
AddText( " send a vIDeo jpg " );
}
// 编码
public static voID EncodeJpeg(WriteableBitmap bmp, Stream dstStream)
{
// Init buffer in FluxJpeg format
int w = bmp.PixelWIDth;
int h = bmp.PixelHeight;
int [] p = bmp.Pixels;
byte [][,] pixelsForJpeg = new byte [ 3 ][,]; // RGB colors
pixelsForJpeg[ 0 ] = new byte [w, h];
pixelsForJpeg[ 1 ] = new byte [w, h];
pixelsForJpeg[ 2 ] = new byte [w, h];
// copy WriteableBitmap data into buffer for FluxJpeg
int i = 0 ;
for ( int y = 0 ; y < h; y ++ )
{
for ( int x = 0 ; x < w; x ++ )
{
int color = p[i ++ ];
pixelsForJpeg[ 0 ][x, y] = ( byte )(color >> 16 ); // R
pixelsForJpeg[ 1 ][x, y] = ( byte )(color >> 8 ); // G
pixelsForJpeg[ 2 ][x, y] = ( byte )(color); // B
}
}
// Encode Image as JPEG
var jpegImage = new FluxJpeg.Core.Image( new colorModel { colorspace = colorSpace.RGB }, pixelsForJpeg);
var encoder = new JpegEncoder(jpegImage, 95 , dstStream);
encoder.Encode();
}
// 解码
public static WriteableBitmap DecodeJpeg(Stream srcStream)
{
// Decode JPEG
var decoder = new FluxJpeg.Core.Decoder.JpegDecoder(srcStream);
var jpegDecoded = decoder.Decode();
var img = jpegDecoded.Image;
img.ChangecolorSpace(colorSpace.RGB);
// Init Buffer
int w = img.WIDth;
int h = img.Height;
var result = new WriteableBitmap(w, h);
int [] p = result.Pixels;
byte [][,] pixelsFromJpeg = img.Raster;
// copy FluxJpeg buffer into WriteableBitmap
int i = 0 ;
for ( int x = 0 ; x < w; x ++ )
{
for ( int y = 0 ; y < h; y ++ )
{
p[i ++ ] = ( 0xFF << 24 ) // A
| (pixelsFromJpeg[ 0 ][x, y] << 16 ) // R
| (pixelsFromJpeg[ 1 ][x, y] << 8 ) // G
| pixelsFromJpeg[ 2 ][x, y]; // B
}
}
return result;
}
此处为视频开始的事件
代码 voID btnVIDeo_Click( object sender, RoutedEventArgs e){
if (source != null )
{
source.Stop();
source.VIDeoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVIDeoCaptureDevice();
VIDeoBrush vBrush = new VIDeoBrush();
vBrush.SetSource(source);
this .rectangleUser.Fill = vBrush;
if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
{
source.Start();
}
AddText( " start vIDeo " );
}
}
voID txtMessage_KeyDown( object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SendMsg();
}
}
这个Demo存在的问题有三个
1,视频流传输到服务器再转到对方客户端的过程有些复杂而且费时,打算采用两种方法解决,一是用Socket通信,二是用双通道推送方式。
2,目前的视频流应该经过压缩后传输,在客户端进行解析,否则如此大的数据量解析是个问题。
3,由于是IIS托管WCF服务,在这个DEMO中有WCF回调客户端的方式,这种方式一旦客户端掉线,服务端回调不到客户端就会出现异常,这种异常靠 try catch解决不了。
4,在某些电脑的ie8上打开视频时会卡死。
如果您看到这篇文章对这几个问题比较了解,兄弟我还是非常想请教一下的,谢谢。
总结以上是内存溢出为你收集整理的Silverlight访问摄像头和麦克风(2)视频对话全部内容,希望文章能够帮你解决Silverlight访问摄像头和麦克风(2)视频对话所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)