java代码实现websocket聊天
时间: 2023-09-21 11:03:28 浏览: 76
java实现socket聊天
它主要分为两个部分:客户端和服务器端。
1. 服务器端代码
```java
// 引入相关包
import java.net.InetSocketAddress;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class WebSocketChatServer extends WebSocketServer {
public WebSocketChatServer( int port ) {
super( new InetSocketAddress( port ) );
}
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
// 连接成功处理
System.out.println( "New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress() );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
// 连接关闭处理
System.out.println( conn + " has been disconnected!" );
}
@Override
public void onMessage( WebSocket conn, String message ) {
// 收到消息处理
System.out.println( conn + ": " + message );
}
@Override
public void onError( WebSocket conn, Exception ex ) {
// 异常处理
System.err.println( "an error occurred on connection " + conn + ":" + ex );
}
public static void main( String[] args ) {
WebSocketChatServer server = new WebSocketChatServer( 8080 );
server.run();
}
}
```
2. 客户端代码
```java
// 引入相关包
import java.net.URI;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class WebSocketChatClient extends WebSocketClient {
public WebSocketChatClient( URI serverUri ) {
super( serverUri );
}
@Override
public void onOpen( ServerHandshake handshakedata ) {
// 连接成功处理
System.out.println( "Connected!" );
}
@Override
public void onClose( int code, String reason, boolean remote ) {
// 连接关闭处理
System.out.println( "Disconnected!" );
}
@Override
public void onMessage( String message ) {
// 收到消息处理
System.out.println( "Received message: " + message );
}
@Override
public void onError( Exception ex ) {
// 异常处理
System.err.println( "an error occurred:" + ex );
}
public static void main( String[] args ) {
try {
WebSocketChatClient client = new WebSocketChatClient( new URI( "ws://localhost:8080" ) );
client.connect();
} catch ( Exception ex ) {
// 异常处理
System.err.println( "an error occurred:" + ex );
}
}
}
```
以上就是 Java 实现的 WebSocket 聊天的代码。注:该代码仅作为演示使用,实际开发中还需要加入异常处理、连接认证等逻辑。
阅读全文