首页  

websocket 聊天室简单例子     所属分类 websocket 浏览量 73
Java-WebSocket 是一个开源的、轻量级的WebSocket客户端和服务器库,它遵循Java API规范(JSR 356)来实现WebSocket协议。

org.java-websocket.Java-WebSocket.1.5.2

ChatServer.java

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

public class ChatServer extends WebSocketServer {

    public ChatServer(int port) {
        super(new InetSocketAddress(port));
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        System.out.println("New connection from: " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {

        // System.out.println("Closed connection to: " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
        System.out.println("Closed connection to: " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Received message: " + message+","+conn.getRemoteSocketAddress());
        // Broadcast the message to all connected clients
        broadcast(conn.getRemoteSocketAddress()+":"+message);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        System.err.println("Error on connection: " + ex+",conn="+conn);
    }

    @Override
    public void onStart() {
    }

    public static void main(String[] args) {
        int port = 8888;
        ChatServer server = new ChatServer(port);
        server.start();
        System.out.println("WebSocket Server started on port: " + port);
    }
}


h5 网页客户端 h5client/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket Chat</title> </head> <body> <input type="text" id="messageInput" placeholder="Type your message"> <button onclick="sendMessage()">Send</button> <hr> <div id="chat"></div> <script> const socket = new WebSocket('ws://localhost:8888'); socket.onopen = (event) => { console.log('WebSocket connection opened:', event); }; socket.onmessage = (event) => { const messageDiv = document.getElementById('chat'); const messageParagraph = document.createElement('p'); messageParagraph.textContent = event.data; messageDiv.appendChild(messageParagraph); }; socket.onclose = (event) => { console.log('WebSocket connection closed:', event); }; function sendMessage() { const messageInput = document.getElementById('messageInput'); const message = messageInput.value; socket.send(message); messageInput.value = ''; } </script> </body> </html>
https://gitee.com/dyyx/work2024/tree/master/demo/websocket/chat

上一篇     下一篇
netty内置编解码器

MQTT与WebSocket

WebSocket通信过程及原理

netty http server 实例

netty 趣事

Netty ChannelPipeline Inbound Outbound