背景:
在通过 websocket 给服务器发送数据时,出现了如下错误
WebSocket connection to 'ws://xxx.xxx.xxx.223:xxxx/' failed: WebSocket opening handshake timed out
解决办法:
去除掉传统的函数调用方式,该种方式虽然可以可以实现WebSocket连接,但是再频繁的调用时,会出现需要重复的创建WebSocket对象,那样相对相对浪费资源,同时也会上述连接超时的错误
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket</title>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("您的浏览器支持 WebSocket!");
/*
打开一个 web socket
ws://localhost:9998/ 表示 socket 连接地址
echo-protocol 表示子协议
*/
var ws = new WebSocket("ws://localhost:9998/", 'echo-protocol');
ws.onopen = function () {