首页 新闻 会员 周边 捐助

JS 通过JSON 连接 websocket

0
悬赏园豆:50 [已解决问题] 解决于 2016-05-30 03:25
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript"type="text/javascript">

var wsUri ="ws://134.91.11.156:6678";
var output;
var msg;

function init() {
output = document.getElementById("output");
testWebSocket();
}

function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "blob";

websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onclose = function(evt) {
onClose(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};



websocket.onerror = function(evt) {
onError(evt)
};
}

function onOpen(evt) {
writeToScreen("CONNECTED to:"+wsUri);
console.log("Websocket CONNECTED to " + wsUri);
doSend('{ "req" : { "params" : { "dirid" : "FractalData@EMPTY" }, "rid" : 0, "sid" : 0 }, "type" : "ListFiles" }');// is the command right?
}// if it send message successful, show measage on the screen

function onClose(evt) {
writeToScreen("DISCONNECTED");
console.log("Websocket DISCONNECTED");
}// show close message if the connent is over

function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: '+evt.data +'</span>');// I want to get the response and show it on screen,using "evt.data" is right? Can I direct show the JSON on the screen?
websocket.close();
}

function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data);
}// if sending is failed,show the message

function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
} // send the command to the server

function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
} // write the message on the screen


</script>
<body onload="init()">

<h2>WebSocket Test</h2>
<div id="output"></div>

</body>

</html>

先附上代码,可以帮我一下代码有什么问题么,因为一直显示连接失败,但是服务器确实是正常的啊,谁能告诉我原因么
kkkoookkkiii的主页 kkkoookkkiii | 初学一级 | 园豆:56
提问于:2016-05-25 21:10
< >
分享
最佳答案
0

前台代码正确,具体还得看后台握手代码,估计是那里有问题,我先附上我后台使用的握手代码,你可以参考一下:

 1         /// <summary>
 2         /// 打包握手信息
 3         /// </summary>
 4         /// <param name="acceptKey">Sec-WebSocket-Accept</param>
 5         /// <returns>数据包</returns>
 6         private static byte[] PackHandShakeData(string acceptKey)
 7         {
 8             /**
 9              * 
10              *  HTTP/1.1 101 Switching Protocols
11                 Upgrade: websocket
12                 Connection: Upgrade
13                 Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
14                 Sec-WebSocket-Protocol: chat
15              * 
16              * */
17 
18             var responseBuilder = new StringBuilder();
19             responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
20             responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
21             responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
22             responseBuilder.Append("Sec-WebSocket-Accept: " + acceptKey + Environment.NewLine + Environment.NewLine);
23             //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);
24             return Encoding.UTF8.GetBytes(responseBuilder.ToString());
25         }
26 
27         /// <summary>
28         /// 生成Sec-WebSocket-Accept
29         /// </summary>
30         /// <param name="handShakeText">客户端握手信息</param>
31         /// <returns>Sec-WebSocket-Accept</returns>
32         private static string GetSecKeyAccept(byte[] handShakeBytes, int bytesLength)
33         {
34             string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
35             string key = string.Empty;
36             Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
37             Match m = r.Match(handShakeText);
38             if (m.Groups.Count != 0)
39             {
40                 key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
41             }
42 
43             //服务端的accept-key生成逻辑
44             //1.取出客户端的key,拼接GUID字符串258EAFA5-E914-47DA-95CA-C5AB0DC85B11
45             //2.创建字符串的SHA1散列
46             //3.转base64字符串
47 
48             byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
49             return Convert.ToBase64String(encryptionString);
50         }

 

拿到客户端socket后,发送握手包:

1 clientSocket.Send(PackHandShakeData(GetSecKeyAccept(state.Buffer, length)));//发送握手包  

 

 

收获园豆:50
过了这个村 | 菜鸟二级 |园豆:262 | 2016-05-26 11:34
其他回答(5)
0

初略看了下,并未发现明显问题。你后端是如何实现的?显示连接失败,是执行的哪个事件?

幻天芒 | 园豆:37207 (高人七级) | 2016-05-26 09:44
0

服务器防火墙端口是否开放。

长蘑菇星人 | 园豆:1832 (小虾三级) | 2016-05-26 09:53
0

那你要给出onerror的信息呀

Yu | 园豆:12990 (专家六级) | 2016-05-26 11:38
0

我知道问题了,是端口号错了,后台给了我错误的TCP端口号,我连接WS字头肯定出错,跟做后台的交流太费劲

kkkoookkkiii | 园豆:56 (初学一级) | 2016-05-30 03:21
0

如果想从服务器端推送消息到客户端的话,个人觉得GoEasy推送还不错,它有Restful API 支持多语言,而且针对java他们还特别做了SDK,使用很简单方便。同时它也支持客户端推送。由于它支持websocket 和polling两种连接方式所以兼顾大多数主流浏览器,低版本的IE浏览器也是支持的,很适合需要快速建立实时web通信的项目。https://goeasy.io相关博客:http://www.cnblogs.com/jishaochengduo/articles/5552645.html

fanqiechaodan | 园豆:202 (菜鸟二级) | 2017-01-09 14:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册