java使用websocket代码
时间: 2023-04-01 22:01:21 浏览: 167
可以使用Java的WebSocket API来实现WebSocket通信。以下是一个简单的Java WebSocket服务器的示例代码:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.Headers;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
@ServerEndpoint("/websocket/{username}")
public class WebSocketServer {
private static final int PORT = 808;
@OnMessage
public void onMessage(Session session, String message, @PathParam("username") String username) throws IOException {
// 处理收到的消息
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), );
server.createContext("/websocket", new WebSocketHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
}
static class WebSocketHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
if ("GET".equals(exchange.getRequestMethod())) {
Headers headers = exchange.getResponseHeaders();
headers.add("Upgrade", "websocket");
headers.add("Connection", "Upgrade");
headers.add("Sec-WebSocket-Accept", "...");
exchange.sendResponseHeaders(101, -1);
Session session = null;
// 创建WebSocket会话
session.getBasicRemote().sendText("连接成功");
}
}
}
}
```
以上代码仅供参考,具体实现需要根据实际需求进行修改。
阅读全文