Js WebSocket

2020-12-16  本文已影响0人  MakerSir

<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:7272");
//申请一个WebSocket对象,参数是服务端地址,同http协议使用http://开头一样,WebSocket协议的url使用ws://开头,另外安全的WebSocket协议使用wss://开头
ws.onopen = function(){
  //当WebSocket创建成功时,触发onopen事件
console.log("open");
  ws.send("hello"); //将消息发送到服务端
}

ws.onmessage = function(e){
  //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
var data = JSON.parse(e.data);
switch(data['type']){
// 服务端ping客户端
case 'ping':
ws.send('{"type":"pong"}');
console.log("ping: "+e.data);
break;;
// 登录 更新用户列表
case 'login':
console.log("login: "+e.data);
//{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
/say(data['client_id'], data['client_name'], data['client_name']+' 加入了聊天室', data['time']);
if(data['client_list'])
{
client_list = data['client_list'];
}
else
{
client_list[data['client_id']] = data['client_name'];
}
flush_client_list();
console.log(data['client_name']+"登录成功");
/
break;
// 发言
case 'say':
console.log("say: "+e.data);
//{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
//say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
break;
// 用户退出 更新用户列表
case 'logout':
console.log("logout: "+e.data);
//{"type":"logout","client_id":xxx,"time":"xxx"}
// say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
//delete client_list[data['from_client_id']];
// flush_client_list();
}
}
ws.onclose = function(e){
  //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
  console.log("close");
}

ws.onerror = function(e){
  //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
  console.log(error);
}

function login()
{
console.log("login:111");
var login_data = '{"type":"login","client_name":"zyx","room_id":"1"}';
console.log("websocket握手成功,发送登录数据:"+login_data);
ws.send(login_data);
}

function send()
{
console.log("send:111");
ws.send('{"type":"say","to_client_id":"all","to_client_name":"222","content":"txt"}');
}

function send2()
{
console.log("send:111");
ws.send('{"type":"say","to_client_id":"7f00000108fc00000011","to_client_name":"222","content":"txt"}');
}

</script>
</head>
<body>
<div onclick="login()" style="width:100px;height:80px;">
登录
</div>

<div onclick="send()" style="width:100px;height:80px;">
发送
</div>

<div onclick="send2()" style="width:100px;height:80px;">
发送2
</div>
</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读