用java写个简单的websocket服务器吧
时间: 2023-09-04 09:13:25 浏览: 84
以下是一个简单的WebSocket服务器的Java代码示例:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class WebSocketServer {
private final int port;
private ArrayList<WebSocketConnection> connections;
public WebSocketServer(int port) {
this.port = port;
this.connections = new ArrayList<>();
}
public void start() {
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("WebSocket server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
WebSocketConnection connection = new WebSocketConnection(clientSocket, this);
connection.start();
connections.add(connection);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void broadcast(String message) {
for (WebSocketConnection connection : connections) {
connection.send(message);
}
}
public void removeConnection(WebSocketConnection connection) {
connections.remove(connection);
}
public static void main(String[] args) {
WebSocketServer server = new WebSocketServer(8080);
server.start();
}
}
```
上述代码中,我们创建了一个WebSocketServer类,它包含了以下几个主要功能:
1. 创建一个ServerSocket实例并监听指定的端口;
2. 当有新的客户端连接时,创建一个WebSocketConnection实例并将其加入到连接列表中;
3. 在连接列表中广播消息;
4. 当一个WebSocket连接关闭时,从连接列表中移除它。
WebSocketConnection类的代码如下所示:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class WebSocketConnection extends Thread {
private final WebSocketServer server;
private final Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public WebSocketConnection(Socket clientSocket, WebSocketServer server) {
this.clientSocket = clientSocket;
this.server = server;
}
public void send(String message) {
out.println(message);
out.flush();
}
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message: " + inputLine);
if (inputLine.equals("exit")) {
break;
}
server.broadcast(inputLine);
}
in.close();
out.close();
clientSocket.close();
server.removeConnection(this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
WebSocketConnection类是一个继承自Thread的类,它用于处理单个WebSocket连接。它包含以下几个主要功能:
1. 创建一个PrintWriter和BufferedReader实例,并通过它们与客户端进行通信;
2. 接收来自客户端的消息,并将其广播给所有连接;
3. 当客户端发送exit消息时,关闭连接并从连接列表中移除。
在本例中,我们只是简单地将接收到的消息广播给所有连接,你可以根据需要修改它的行为。
最后,我们可以通过运行下面的代码来启动WebSocket服务器:
```java
WebSocketServer server = new WebSocketServer(8080);
server.start();
```
现在,你可以使用WebSocket协议与该服务器进行通信了。
阅读全文