浏览器使用WebSocket实时通讯
如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接:<font color="rgb(0, 0, 136)">var</font> socket = <font color="rgb(0, 0, 136)">new</font> WebSocket(<font color="rgb(0, 153, 0)">"ws://172.0.0.1:8080/SpringWebSocketPush/websck"</font>);与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
该套接口对象有四个用来监听套接口事件的回调: socket.onopen = function(){
//打开
}
socket.onmessage = function(){
//在event.data消息数据
}
socket.onclose = function(){
//关闭WebSocket
}
socket.onerror = function(){
//错误触发
}
通过套接口发送数据,调用socket.send: <font color="rgb(79, 79, 79)">socket</font>.<font color="rgb(79, 79, 79)">send</font>(message)
代码附上:<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
<title>WebSocket</title>
</head>
<body>
</body>
<script>
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/myapp");
socket.onmessage = function(event) {
alert("Received data from websocket: " + event.data);
}
socket.onopen = function(event) {
alert("Web Socket opened!");
};
socket.onclose = function(event) {
alert("Web Socket closed.");
};
} else {
alert("Your browser does not support Websockets. (Use Chrome)");
}
function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("The socket is not open.");
}
}
</script>
</html>
页:
[1]