java WebSocket 服务端代码

2022-02-16  本文已影响0人  IT祖师爷

ackage org.fh.plugins.ChatServer;

import java.net.InetSocketAddress;

import java.net.UnknownHostException;

import org.java_websocket.WebSocket;

import org.java_websocket.framing.Framedata;

import org.java_websocket.handshake.ClientHandshake;

import org.java_websocket.server.WebSocketServer;

/**

* 说明:websocket服务端

* 作者:FH Admin

* from:fhadmin.cn

*/

public class ChatServer extends WebSocketServer{

public BulletChatServer(int port) throws UnknownHostException {

super(new InetSocketAddress(port));

}

public BulletChatServer(InetSocketAddress address) {

super(address);

}

/**

* 客户端发送消息到服务器时触发事件

*/

@Override

public void onMessage(WebSocket conn, String message){

message = message.toString();

if(null != message && message.startsWith("[video313596790]")){

this.userjoin(message.replaceFirst("\\[video313596790\\]", ""),conn);

}else{

BulletChatServerPlool.sendMessage(message.toString());//向所有在线用户发送消息

}

}

public void onFragment( WebSocket conn, Framedata fragment ) {

}

/**

* 用户加入处理

* @param user

*/

public void userjoin(String user, WebSocket conn){

BulletChatServerPlool.addUser(user,conn); //向连接池添加当前的连接对象

}

/**

* 用户下线处理

* @param user

*/

public void userLeave(WebSocket conn){

BulletChatServerPlool.removeUser(conn); //在连接池中移除连接

}

/**

* 触发连接事件

*/

@Override

public void onOpen( WebSocket conn, ClientHandshake handshake ) {}

/**

* 触发关闭事件

*/

@Override

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

userLeave(conn);

}

/**

* 触发异常事件

*/

@Override

public void onError( WebSocket conn, Exception ex ) {

if( conn != null ) {}

}

@Override

public void onStart() {}

}

上一篇下一篇

猜你喜欢

热点阅读