好久没有碰前端的代码了。。。
今天测试WebSocket功能,Client端:使用Html+JavaScript,通过浏览器解析后,当做客户端;
客户端代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
WebSocket Client
</title>
</head>
<body>
<script>
var socket;
//check current explorer wether support WebSockek
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:7070/helloWs"); // =非英文等号!
//event : msg from server
socket.onmessage = function(event) {
console.log("receive msg:" + event.data);
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + event.data;
}
//eq open WebSocket
socket.onopen = function(event) {
var rt = document.getElementById("responseText");
rt.value = "open WebSocket";
}
socket.onclose = function(event) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "close WebSocket";
}
} else {
alert("current exploer not support websocket")
}
//send msg to WebSocket Server
function send(message) {
if (socket.readyState == WebSocket.OPEN) {
//send msg to WebSocket by socket
socket.send(message);
} else {
alert("WebSocket is not open")
}
}
</script>
<form onsubmit="return false">
<textarea name="message" style="height: 300px; width: 300px;"></textarea>
<input type="button" value="发送消息" onclick="send(this.form.message.value)">
<textarea id="responseText" style="height: 300px; width: 300px;"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
把上面的html代码直接保持为html文件,双机打开后,发现并没有连接到服务端的WebSocket上;打开F12,可以看到在Console标签下有错误信息:Uncaught SyntaxError: Invalid or unexpected token (at front.html:14:12)
该提示信息,一般是指在代码找中出现了非英文符号(注释或者字符串是可以的)
socket = new WebSocket("ws://localhost:7070/helloWs"); // =非英文等号!
修改为英文等号,即可;
刷新页面,看到可以正常连接到服务端了。。。