在IIS上搭建WebSocket服务器(三)
编写客户端代码1.新建一个*.html文件。ws = new WebSocket('ws://192.168.85.128:8086/Handler1.ashx?user=' + $("#user").val());这个地方的IP和端口号对应着我们搭建在IIS上的WebSocket服务器<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<title></title>
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
var ws;
$().ready(function () {
$('#conn').click(function () {
//ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Handler1.ashx?user=' + $("#user").val());
ws = new WebSocket('ws://192.168.85.128:8086/Handler1.ashx?user=' + $("#user").val());
//var host = 'ws://192.168.85.128:8085/api/WSChat?user='+$("#user").val();
//var host = "ws://192.168.85.128:8085/api/WSChat";
//webSocket = new WebSocket(host);
$('#msg').append('<p>正在连接</p>');
ws.onopen = function () {
$('#msg').append('<p>已经连接</p>');
}
ws.onmessage = function (evt) {
$('#msg').append('<p>' + evt.data + '</p>');
}
ws.onerror = function (evt) {
$('#msg').append('<p>' + JSON.stringify(evt) + '</p>');
}
ws.onclose = function () {
$('#msg').append('<p>已经关闭</p>');
}
});
$('#close').click(function () {
ws.close();
});
$('#send').click(function () {
if (ws.readyState == WebSocket.OPEN) {
ws.send($("#to").val() + "|" + $('#content').val());
}
else {
$('#tips').text('连接已经关闭');
}
});
});
</script>
</head>
<body>
<div>
<input id="user" type="text" />
<input id="conn" type="button" value="连接" />
<input id="close" type="button"value="关闭"/><br />
<span id="tips"></span>
<input id="content" type="text" />
<input id="send" type="button"value="发送"/><br />
<input id="to" type="text" />目的用户
<div id="msg">
</div>
</div>
</body>
</html>2.客户端A和客户端B通信效果在浏览器中分别打开两个窗口,左边为客户端A,右边为客户端B,点击“连接”按钮,AB客户端分别与服务器建立连接填写要发送的内容,即可看到A和B互相发送的信息了,即实现了AB客户端实现了WebSocket即时通信。
页:
[1]