websock通信java完整源码
时间: 2023-07-31 15:00:41 浏览: 76
java WebSocket源码
5星 · 资源好评率100%
以下是一个使用Java编写的基本的WebSocket通信的完整源码示例:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class WebSocketServer {
private ServerSocket serverSocket;
private List<WebSocketClientHandler> clients;
public WebSocketServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
clients = new ArrayList<>();
}
public void start() {
System.out.println("WebSocket Server is running on port " + serverSocket.getLocalPort());
while (true) {
try {
Socket socket = serverSocket.accept();
WebSocketClientHandler handler = new WebSocketClientHandler(socket, this);
clients.add(handler);
handler.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void broadcast(String message) {
for (WebSocketClientHandler client : clients) {
client.sendMessage(message);
}
}
public static void main(String[] args) {
try {
WebSocketServer server = new WebSocketServer(8080);
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class WebSocketClientHandler extends Thread {
private Socket socket;
private WebSocketServer server;
private BufferedReader reader;
private PrintWriter writer;
public WebSocketClientHandler(Socket socket, WebSocketServer server) {
this.socket = socket;
this.server = server;
try {
InputStream input = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
writer = new PrintWriter(output, true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String message;
while (true) {
try {
message = reader.readLine();
server.broadcast(message);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void sendMessage(String message) {
writer.println(message);
}
}
```
上述代码展示了一个简单的WebSocket服务器和一个客户端处理程序。服务器通过监听指定的端口接受传入的连接,并将连接的客户端保存到客户端列表中。在客户端线程中,服务器将消息从一个客户端广播到所有其他客户端。
阅读全文