using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebSocketServer wsServer = new WebSocketServer();
if (!wsServer.Setup("192.168.1.150", 8060))
{
//设置IP 与 端口失败 通常是IP 和端口范围不对引起的 IPV4 IPV6
}
if (!wsServer.Start())
{
//开启服务失败 基本上是端口被占用或者被 某杀毒软件拦截造成的
return;
}
wsServer.NewSessionConnected += (session) =>
{
//有新的连接
};
wsServer.SessionClosed += (session, reason) =>
{
//有断开的连接
};
wsServer.NewMessageReceived += (session, message) =>
{
session.Send(message);
//接收到新的文本消息
};
wsServer.NewDataReceived += (session, bytes) =>
{
//接收到新的二进制消息
};
Console.ReadKey();
wsServer.Stop();
}
}
}
前端
<html>
<head>
<title>websocket</title>
<script src="jquery-1.7.2.js"></script>
<style>
#ServerInfo {
height: 500px;
width: 500px;
background: url(200812910493588_2.jpg);
overflow: scroll;
font-size: 20px;
font-family: 微软雅黑;
}
#div_id_UserSend {
width: 500px;
}
</style>
</head>
<body>
<div id="ServerInfo">
</div>
<div id="div_id_UserSend">
<textarea id="textarea_id_UserInfo"></textarea>
<a href="javascript:;" id="InfoSend">发送消息</a>
<a href="javascript:;" id="GetStatus">获取状态</a>
</div>
<script type="text/javascript">
var output = $("#ServerInfo");
var websocket=null;
var wsUri = "ws://echo.websocket.org/";
testWebSocket();
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
output.append("创建链接<br/>");
};
websocket.onclose = function (evt) {
output.append("关闭连接<br/>");
};
websocket.onmessage = function (evt) {
output.append("来自服务器消息:" + evt.data + "<br/>");
console.log(evt);
};
websocket.onerror = function (evt) {
output.append("链接失败!<br/>");
};
}
//发送消息
$("#InfoSend").click(function () {
if (websocket.readyState!=1) { alert("socket未连接"); return; }
websocket.send($("#textarea_id_UserInfo").val());
});
$("#GetStatus").click(function () {
alert(websocket.readyState);
});
</script>
</body>
</html>