可以實現的
//?創建壹個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的狀態。