<!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>
先附上代码,可以帮我一下代码有什么问题么,因为一直显示连接失败,但是服务器确实是正常的啊,谁能告诉我原因么
前台代码正确,具体还得看后台握手代码,估计是那里有问题,我先附上我后台使用的握手代码,你可以参考一下:
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)));//发送握手包
初略看了下,并未发现明显问题。你后端是如何实现的?显示连接失败,是执行的哪个事件?
服务器防火墙端口是否开放。
那你要给出onerror的信息呀
我知道问题了,是端口号错了,后台给了我错误的TCP端口号,我连接WS字头肯定出错,跟做后台的交流太费劲
如果想从服务器端推送消息到客户端的话,个人觉得GoEasy推送还不错,它有Restful API 支持多语言,而且针对java他们还特别做了SDK,使用很简单方便。同时它也支持客户端推送。由于它支持websocket 和polling两种连接方式所以兼顾大多数主流浏览器,低版本的IE浏览器也是支持的,很适合需要快速建立实时web通信的项目。https://goeasy.io相关博客:http://www.cnblogs.com/jishaochengduo/articles/5552645.html