<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:7272");
//申請(qǐng)一個(gè)WebSocket對(duì)象,參數(shù)是服務(wù)端地址,同http協(xié)議使用http://開頭一樣病梢,WebSocket協(xié)議的url使用ws://開頭断部,另外安全的WebSocket協(xié)議使用wss://開頭
ws.onopen = function(){
//當(dāng)WebSocket創(chuàng)建成功時(shí),觸發(fā)onopen事件
console.log("open");
ws.send("hello"); //將消息發(fā)送到服務(wù)端
}
ws.onmessage = function(e){
//當(dāng)客戶端收到服務(wù)端發(fā)來(lái)的消息時(shí),觸發(fā)onmessage事件匪煌,參數(shù)e.data包含server傳遞過(guò)來(lái)的數(shù)據(jù)
var data = JSON.parse(e.data);
switch(data['type']){
// 服務(wù)端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;
// 發(fā)言
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){
//當(dāng)客戶端收到服務(wù)端發(fā)送的關(guān)閉連接請(qǐng)求時(shí)豹爹,觸發(fā)onclose事件
console.log("close");
}
ws.onerror = function(e){
//如果出現(xiàn)連接裆悄、處理、接收臂聋、發(fā)送數(shù)據(jù)失敗的時(shí)候觸發(fā)onerror事件
console.log(error);
}
function login()
{
console.log("login:111");
var login_data = '{"type":"login","client_name":"zyx","room_id":"1"}';
console.log("websocket握手成功光稼,發(fā)送登錄數(shù)據(jù):"+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;">
發(fā)送
</div>
<div onclick="send2()" style="width:100px;height:80px;">
發(fā)送2
</div>
</body>
</html>