///// <summary> ///// 升级协议的回复处理 ///// </summary> int UpgradeResponse(byte[] buffer, int bufferAvailable) { //获取服务器发来的升级确认 ByteArray ba = new ByteArray(buffer, bufferAvailable); string clientRequest = ba.ReadStringBytes(Encoding.ASCII, ba.ReadEnableSize); string[] datas = clientRequest.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); try { for (int i = 0; i < datas.Length; i++) { if (datas[i].Contains("Sec-WebSocket-Accept")) { IsUpgrade = true; onUpgradeResult?.Invoke(this, true); Log.I("WS协议升级成功!"); break; } } } catch (Exception e) { Log.E(e.Message); } if (false == IsUpgrade) { Log.E("WebSocket协议升级失败"); onUpgradeResult?.Invoke(this, false); Close(); } return(bufferAvailable); }
/// <summary> /// 升级协议为WebSocket协议 /// </summary> int Upgrade(byte[] buffer, int bufferAvailable) { //获取客户端发来的升级协议KEY ByteArray ba = new ByteArray(buffer, bufferAvailable); string clientRequest = ba.ReadStringBytes(Encoding.ASCII, ba.ReadEnableSize); string[] datas = clientRequest.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); string value = null; try { for (int i = 0; i < datas.Length; i++) { if (datas[i].Contains("Sec-WebSocket-Key")) { string[] keyValue = datas[i].Split(':'); value = keyValue[1].Trim(); break; } } } catch (Exception e) { Log.E(e.Message); value = null; } if (null == value) { Log.E("WebSocket协议升级失败"); onUpgradeResult?.Invoke(this, false); Close(); return(0); } byte[] responseBytes = _protocolProcess.CreateUpgradeResponse(value); //回执升级协议 SendBytes(responseBytes); IsUpgrade = true; onUpgradeResult?.Invoke(this, true); return(bufferAvailable); }