HTML5WebSocket实现实时视频文字传输
HTML5的Canvas 可以实现绘图 然后应该是这样写的
02
|
<html xmlns="http://www.w3.org/1999/xhtml">
|
08
|
<input type="text" id="msg" value="beyond is number one!" />
|
09
|
<button onclick="sendMsg()">走你~</button>
|
11
|
<canvas id="myCanvas" style="width: 400px; height: 500px;"></canvas>
|
12
|
<div id="output"></div>
|
13
|
<script type="text/javascript">
|
14
|
var wsServer = 'ws://192.168.10.242:9999/webSocket.ashx'; //服务器地址
|
15
|
//var wsServer = 'ws://localhost:36027/webSocket.ashx'; //服务器地址
|
16
|
var canvas = document.getElementById("myCanvas");
|
17
|
var context = canvas.getContext("2d");
|
18
|
var websocket = new WebSocket(wsServer); //创建WebSocket对象
|
19
|
websocket.onopen = function (evt) {
|
23
|
websocket.onclose = function (evt) {
|
26
|
writeToScreen("连接关闭");
|
28
|
websocket.onmessage = function (evt) {
|
29
|
//收到服务器消息,使用evt.data提取
|
30
|
var image = new Image();
|
31
|
image.onload = function () {
|
33
|
context.clearRect(0, 0,
|
34
|
canvas.width, canvas.height);
|
35
|
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
37
|
image.src = URL.createObjectURL(evt.data);
|
39
|
websocket.onerror = function (evt) {
|
41
|
writeToScreen(evt.message);
|
44
|
if (websocket.readyState == websocket.OPEN) {
|
45
|
msg = document.getElementById("msg").value;
|
47
|
writeToScreen("发送成功!");
|
49
|
writeToScreen("连接失败!");
|
53
|
function writeToScreen(message) {
|
54
|
var pre = document.createElement("p");
|
55
|
pre.style.wordWrap = "break-word";
|
56
|
pre.innerHTML += message;
|
57
|
output.appendChild(pre);
|
通过 context.drawImage(image, 0, 0, canvas.width, canvas.height); 来绘制图像
websocket接到数据后通过
image.src = URL.createObjectURL(evt.data);转换成图片对象
ok 这样能实现接收图片了,然后服务端发送的时候
1
|
//Buffer里面为你的图片数据 你可以通过文件流的方式来打开
|
2
|
await socket.SendAsync(buffer, WebSocketMessageType.Binary,true, CancellationToken.None);
|
3
|
//注意此时WebSocketMessageType 为Binary二进制流
|
然后我实现了一个 读取本地文件夹 每隔1秒发送图片给网页的服务端
部分代码如下
01
|
string imgPath = HttpContext.Current.Server.MapPath("images");
|
02
|
string[] files = Directory.GetFiles(imgPath);
|
03
|
for (int i = 0; i < files.Length; i++)
|
05
|
using (FileStream fs = new FileStream(files[i], FileMode.Open))
|
07
|
byte[] imgData = new byte[fs.Length];
|
08
|
fs.Read(imgData, 0, imgData.Length);
|
09
|
//buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
|
10
|
buffer = new ArraySegment<byte>(imgData);
|
11
|
// Asynchronously send a message to the client
|
12
|
await socket.SendAsync(buffer, WebSocketMessageType.Binary,
|
13
|
true, CancellationToken.None);
|
16
|
if (i == files.Length - 1)
|
这样图像传输解决了,然后实现套接字 就可以传输实时图片了。
我做了一个Windows Phone的客户端不断的采集图片发送给服务器 然后服务器接到图片发送给浏览器的Demo 就不贴代码了 上图!
(这张图是在Windows Phone模拟器里面的IE浏览器上 证明了 它支持WebSocket)
(Windows 上的客户端 ^.^ Windows Phone Windows 8都能的 )
上面说的仅仅是简单的演示程序 距离做项目还差的很远,写这篇文章为的是给大家一个信心... Windows 8&Windows Phone也可以的...