-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketServer.java
More file actions
140 lines (111 loc) · 4.68 KB
/
WebSocketServer.java
File metadata and controls
140 lines (111 loc) · 4.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.util.*;
import java.util.Base64;
public class WebSocketServer {
private static List<String> messages = new ArrayList<>();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("WebSocket Server is running on port 8080...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
new Thread(() -> handleClient(clientSocket)).start();
}
} catch (IOException e) {
System.err.println("Server error: " + e.getMessage());
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) {
try {
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
// Perform WebSocket handshake
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String data = reader.readLine();
String key = "";
while (!data.isEmpty()) {
if (data.startsWith("Sec-WebSocket-Key:")) {
key = data.substring(19).trim();
}
data = reader.readLine();
}
// Send handshake response
String accept = Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-1").digest(
(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes()
)
);
String response = "HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " + accept + "\r\n\r\n";
out.write(response.getBytes());
System.out.println("WebSocket handshake completed");
// Handle messages
while (true) {
String message = receiveMessage(in);
if (message == null) break;
System.out.println("Received: " + message);
String result = processRequest(message);
sendMessage(out, result);
}
clientSocket.close();
System.out.println("Client disconnected");
} catch (Exception e) {
System.err.println("Client handler error: " + e.getMessage());
}
}
private static String receiveMessage(InputStream in) throws IOException {
int b = in.read();
if (b == -1) return null;
int opcode = b & 0x0F;
if (opcode == 8) return null; // Close frame
b = in.read();
int length = b & 0x7F;
byte[] masks = new byte[4];
in.read(masks);
byte[] data = new byte[length];
in.read(data);
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (data[i] ^ masks[i % 4]);
}
return new String(data);
}
private static void sendMessage(OutputStream out, String message) throws IOException {
byte[] data = message.getBytes();
out.write(0x81); // Text frame
out.write(data.length);
out.write(data);
out.flush();
}
private static String processRequest(String request) {
String[] parts = request.split("\\|", 2);
String method = parts[0];
switch (method) {
case "HELLO":
String name = parts.length > 1 ? parts[1] : "Guest";
return "Hello, " + name + "!";
case "ADD":
String[] numbers = parts[1].split(",");
int a = Integer.parseInt(numbers[0]);
int b = Integer.parseInt(numbers[1]);
return String.valueOf(a + b);
case "SEND":
String message = parts.length > 1 ? parts[1] : "";
messages.add(message);
System.out.println("Message stored: " + message);
return "Message received";
case "GETALL":
if (messages.isEmpty()) {
return "No messages";
}
return String.join(";;", messages);
default:
return "Unknown method";
}
}
}