// 创建一个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的状态。
aflax,有个已经封装好的js叫做socketJS原理就是利用flash,如果你的程序不考虑iphone用户,可以考虑这个解决方法
http://download.csdn.net/detail/enjoy_lhl/5672205
可以下载一下,如果你有编程基础可以很快上手,下载不需要积分的