java写一段websocket的服务端
时间: 2023-03-27 18:05:07 浏览: 115
你好,以下是一段使用 Java 编写的 WebSocket 服务端代码:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
public class WebSocketServer {
private static final int PORT = 808;
private static final Charset CHARSET = Charset.forName("UTF-8");
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int readyChannels = selector.select();
if (readyChannels == ) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
socketChannel.close();
continue;
}
buffer.flip();
CharBuffer charBuffer = CHARSET.decode(buffer);
String message = charBuffer.toString().trim();
System.out.println("Received message: " + message);
socketChannel.write(CHARSET.encode("Server received your message: " + message));
}
keyIterator.remove();
}
}
}
}
```
以上代码实现了一个简单的 WebSocket 服务端,监听 808 端口,接收客户端发送的消息并回复。当客户端连接时,服务端会注册一个 OP_ACCEPT 事件,当客户端发送消息时,服务端会注册一个 OP_READ 事件。在 OP_READ 事件中,服务端会读取客户端发送的消息并回复。
阅读全文