String str = new String(data, CHARSET);
String[] arr = str.split("\r\n");
String[] temp = arr[0].split(" ");
Map<String, String> map = this.toMap(arr);
String base64 = generateWebSocketAccept((String)map.get("Sec-WebSocket-Key"));
StringBuffer sb = new StringBuffer(200);
sb.append(temp[2]).append(" 101 Switching Protocols\r\n");
sb.append("Upgrade: websocket\r\n");
sb.append("Connection: Upgrade\r\n");
sb.append("Sec-WebSocket-Accept: ").append(base64).append("\r\n\r\n");
其中最重要的是最后几个换行不要丢,将字符串转成byte[]写给客户端即可
public static String generateWebSocketAccept(String webSocketKey) {
System.out.println(webSocketKey);
try {
String acc = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
MessageDigest sh1 = MessageDigest.getInstance("SHA1");
sh1.update(acc.getBytes(CHARSET), 0, acc.length());
return Base64.getEncoder().encodeToString(sh1.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not found", e);
}
}
收到的掩码转换文章来源:https://www.toymoban.com/news/detail-716098.html
int i, j;
for(i=0, j=0; i<data.length; i++, j++) {
data[j] = (byte) (data[i] ^ masks[j % 4]);
}
下面是服务器向客户端发送消息文章来源地址https://www.toymoban.com/news/detail-716098.html
public byte[] doSend(String mess) throws IOException{
byte[] rawData = mess.getBytes();
int frameCount = 0;
byte[] frame = new byte[10];
frame[0] = (byte) 129;
if(rawData.length <= 125){
frame[1] = (byte) rawData.length;
frameCount = 2;
}else if(rawData.length >= 126 && rawData.length <= 65535){
frame[1] = (byte) 126;
int len = rawData.length;
frame[2] = (byte)((len >> 8 ) & (byte)255);
frame[3] = (byte)(len & (byte)255);
frameCount = 4;
}else{
frame[1] = (byte) 127;
int len = rawData.length;
frame[2] = (byte)((len >> 56 ) & (byte)255);
frame[3] = (byte)((len >> 48 ) & (byte)255);
frame[4] = (byte)((len >> 40 ) & (byte)255);
frame[5] = (byte)((len >> 32 ) & (byte)255);
frame[6] = (byte)((len >> 24 ) & (byte)255);
frame[7] = (byte)((len >> 16 ) & (byte)255);
frame[8] = (byte)((len >> 8 ) & (byte)255);
frame[9] = (byte)(len & (byte)255);
frameCount = 10;
}
int bLength = frameCount + rawData.length;
byte[] reply = new byte[bLength];
int bLim = 0;
for(int i=0; i<frameCount;i++){
reply[bLim] = frame[i];
bLim++;
}
for(int i=0; i<rawData.length;i++){
reply[bLim] = rawData[i];
bLim++;
}
return reply;
}
到了这里,关于java实现websocket握手协议的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!