// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:8080')
// 打开Socket
socket.onopen = function(event) {
// 发送一个初始化消息
socket.send('I am the client and I\'m listening!')
// 监听消息
socket.onmessage = function(event) {
console.log('Client received a message',event)
}
// 监听Socket的关闭
socket.onclose = function(event) {
console.log('Client notified socket has closed',event)
}
// 关闭Socket....
//socket.close()
}
参数为URL,ws表示WebSocket协议。onopen、onclose和onmessage方法把事件连接到Socket实例上。每个方法都提供了一个事件,以表示Socket的状态。
<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:100pxheight:80px">
登录
</div>
<div onclick="send()" style="width:100pxheight:80px">
发送
</div>
<div onclick="send2()" style="width:100pxheight:80px">
发送2
</div>
</body>
</html>