|
|
|
|
@ -58,19 +58,42 @@ public class WebSocketServer {
|
|
|
|
|
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
|
|
|
|
|
|
|
|
|
|
// 读取HTTP请求头
|
|
|
|
|
String line = reader.readLine();
|
|
|
|
|
if (line == null) return;
|
|
|
|
|
String firstLine = reader.readLine();
|
|
|
|
|
if (firstLine == null) {
|
|
|
|
|
socket.close();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 读取所有请求头
|
|
|
|
|
Map<String, String> headers = new HashMap<>();
|
|
|
|
|
String line;
|
|
|
|
|
while ((line = reader.readLine()) != null && !line.isEmpty()) {
|
|
|
|
|
int colonIndex = line.indexOf(':');
|
|
|
|
|
if (colonIndex > 0) {
|
|
|
|
|
String key = line.substring(0, colonIndex).trim();
|
|
|
|
|
String value = line.substring(colonIndex + 1).trim();
|
|
|
|
|
headers.put(key, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 判断是HTTP请求还是WebSocket握手
|
|
|
|
|
if (line.startsWith("GET / HTTP")) {
|
|
|
|
|
if (firstLine.startsWith("GET / HTTP") && !headers.containsKey("Upgrade")) {
|
|
|
|
|
// 返回HTML页面
|
|
|
|
|
serveHtmlPage(socket);
|
|
|
|
|
} else if (line.contains("Upgrade: websocket")) {
|
|
|
|
|
} else if (headers.containsKey("Upgrade") && "websocket".equalsIgnoreCase(headers.get("Upgrade"))) {
|
|
|
|
|
// WebSocket握手
|
|
|
|
|
performWebSocketHandshake(socket, reader);
|
|
|
|
|
performWebSocketHandshake(socket, headers);
|
|
|
|
|
} else {
|
|
|
|
|
socket.close();
|
|
|
|
|
}
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.err.println("处理客户端失败: " + e.getMessage());
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
try {
|
|
|
|
|
socket.close();
|
|
|
|
|
} catch (IOException ex) {
|
|
|
|
|
// ignore
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@ -89,18 +112,11 @@ public class WebSocketServer {
|
|
|
|
|
socket.close();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void performWebSocketHandshake(Socket socket, BufferedReader reader) throws Exception {
|
|
|
|
|
String key = null;
|
|
|
|
|
String line;
|
|
|
|
|
|
|
|
|
|
// 读取请求头
|
|
|
|
|
while ((line = reader.readLine()) != null && !line.isEmpty()) {
|
|
|
|
|
if (line.startsWith("Sec-WebSocket-Key:")) {
|
|
|
|
|
key = line.substring(19).trim();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
private void performWebSocketHandshake(Socket socket, Map<String, String> headers) throws Exception {
|
|
|
|
|
String key = headers.get("Sec-WebSocket-Key");
|
|
|
|
|
|
|
|
|
|
if (key == null) {
|
|
|
|
|
System.err.println("缺少Sec-WebSocket-Key");
|
|
|
|
|
socket.close();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
@ -118,6 +134,8 @@ public class WebSocketServer {
|
|
|
|
|
socket.getOutputStream().write(response.getBytes(StandardCharsets.UTF_8));
|
|
|
|
|
socket.getOutputStream().flush();
|
|
|
|
|
|
|
|
|
|
System.out.println("WebSocket握手成功");
|
|
|
|
|
|
|
|
|
|
// 创建WebSocket客户端处理器
|
|
|
|
|
WebSocketClient client = new WebSocketClient(socket, this);
|
|
|
|
|
new Thread(client).start();
|
|
|
|
|
|