写文不容易,请尊重原创:转载注明 http://blog.youkuaiyun.com/meng6098
Websocket的环境支持:
1.支持html5的浏览器 经测试ie10和google可以用
2.Net服务器环境,.Net 4.5,IIS 8,win8,windows server2013,及以上版本。(这点很重要,我买了一个虚拟空间是iis7.5的,结果这个简陋聊天室放上去无法链接。)
Websocket程序知识点:
Websocket的客户端代码知识点:
<script type="text/javascript">
<!--申请一个Websocket对象,地址为服务器一般处理程序地址,同http协议http://开头一样,WebSocket协议的URL使用ws://开头,另外安全的WebSocket协议使用wss://开头-->
var socket= new WebSocket(“ws://aiwantopws.com/WebSocketHandler.ashx”);
<!--WebSocket发送消息方法-->
socket.send(“Hello!”);
<!--WebSocket关系方法-->
socket.close();
<!--监听事件-->
Socket.addEventListener("close", function (evt) { }, false);//监听关闭事件
Socket.addEventListener("open", function (evt) { }, false);//监听创建对象事件
Socket.addEventListener("message", function (evt) { }, false);//监听消息事件
Socket.addEventListener("error", function (evt) { }, false);//监听错误事件
</script>
简陋聊天室简单的代码实现:
1. Index页输入用户名,跳转操作页面default页
2.
<script type="text/javascript">
var socket;
var req = document.referrer;
//判断来源
if(req=="http://aiwantopws.com/index.aspx"||req== "http://aiwantopws.com/index.aspx") {
//获取Get的用户名
var uname = GetQueryString("uname");
if (uname!=null) {
$(document).ready(function () {
//判断浏览器是否支持HTML5 Web Sockets,这里引用了一个modernizr-2.5.3.js包
if (!Modernizr.websockets) {
alert("该浏览器不支持 HTML5 Web Sockets!");
return;
}
//创建WebSocket对象。
socket=new WebSocket("ws://aiwantopws.com/WebSocketHandler.ashx");
//添加监听事件,这里我用json作为来回信息传递
//当用户链接(创建对象)时。
socket.addEventListener("open", function (evt) {
//发送该用户的用户名到服务器。
socket.send("{\"uname\":\"" + uname + "\"}");
$("#divHistory").append('<h3>Connection Opened with the server.</h3>');
}, false);
//当用户执行关闭方法时,
socket.addEventListener("close", function (evt) {
$("#divHistory").append('<h3>Connection was closed. :' + evt.reason + '</h3>');
}, false);
//有消息从服务器传送过来时执行
socket.addEventListener("message", function (evt) {
显示消息
更新在线人数(因为在线多少人在服务器端更新)
}, false);
//出现异常时
socket.addEventListener("error", function (evt) {
显示错误
}, false);
//发送消息
$("#btnSend").click(function () {
判断链接状态 {
发送消息
}
else {
显示该用户断线
}
});
//销毁对象
$("#btnStop").click(function () {
socket.close();
});
});
} else {
window.location.href = '/index.aspx';
}
} else {
window.location.href = '/index.aspx';
}
</script>