用JAVA分别实现WebSocket客户端与服务端


最近公司在搞一个项目刚好需要用到WebSocket技术来实现实时数据的传输,因为之前也没接触过,所以捣鼓了好些天,最近恰巧有空就写写。有误的地方还请大牛们能及时指正。

项目背景:基于spring+spring MVC+mybatis框架的maven项目

服务端:

 1、添加Jar包依赖:

<dependency>
  <groupId>javax.websocketgroupId>
  <artifactId>javax.websocket-apiartifactId>
  <version>1.1version>
  <scope>providedscope>
dependency>

 2、创建一个WebSocket服务端类MyWebSocketServer,并在类前添加@ServerEndpoint(value = "/websocket")注解,@ServerEndpoint(value = "/websocket")注释端点表示将 WebSocket 服务端运行在 ws://[Server IP 或域名]:[Server 端口]/项目名/websocket 的访问端点

 3、实现onOpenonCloseonMessageonError等方法

实例代码:

MyWebSocketServer 类

import java.io.IOException;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;

@ServerEndpoint(value = "/websocket")
public class MyWebSocketServer {
  
private Logger logger = Logger.getLogger(MyWebSocketServer.class);   private Session session;   /**   * 连接建立后触发的方法    */   @OnOpen   public void onOpen(Session session){     this.session = session;     logger.info("onOpen"+session.getId());     WebSocketMapUtil.put(session.getId(),this);   }
  
/**   * 连接关闭后触发的方法   */   @OnClose   public void onClose(){     //从map中删除     WebSocketMapUtil.remove(session.getId());     logger.info("====== onClose:"+session.getId()+" ======");   }
  
/**    * 接收到客户端消息时触发的方法    */   @OnMessage   public void onMessage(String params,Session session) throws Exception{     //获取服务端到客户端的通道     MyWebSocketServer myWebSocket = WebSocketMapUtil.get(session.getId());     logger.info("收到来自"+session.getId()+"的消息"+params);     String result = "收到来自"+session.getId()+"的消息"+params;     //返回消息给Web Socket客户端(浏览器)     myWebSocket.sendMessage(1,”成功!”,result);   }

  
/**    * 发生错误时触发的方法   */   @OnError   public void onError(Session session,Throwable error){     logger.info(session.getId()+"连接发生错误"+error.getMessage());     error.printStackTrace();   }   public void sendMessage(int status,String message,Object datas) throws IOException{     JSONObject result = new JSONObject();     result.put("status", status);     result.put("message", message);     result.put("datas", datas); this.session.getBasicRemote().sendText(result.toString()); } }


WebSocketMapUtil 工具类

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class WebSocketMapUtil {

  public static ConcurrentMap webSocketMap = new ConcurrentHashMap<>();

  public static void put(String key, MyWebSocketServer myWebSocketServer){
       webSocketMap.put(key, myWebSocketServer);
    }

    public static MyWebSocketServer get(String key){
         return webSocketMap.get(key);
    }

    public static void remove(String key){
         webSocketMap.remove(key);
    }
 
    public static Collection getValues(){
        return webSocketMap.values();
    }
}

 客户端:

 1、添加Jar包依赖:

<dependency>
  <groupId>org.java-websocketgroupId>
  <artifactId>Java-WebSocketartifactId>
  <version>1.3.8version>
dependency>

 2、创建Web Socket客户端类MyWebSocketClient,并继承WebSocketClient

 3、实现构造器,重写onOpenonCloseonMessageonError等方法

实例代码:

MyWebSocketClient 类

import java.net.URI;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.log4j.Logger;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

public class MyWebSocketClient extends WebSocketClient{

  Logger logger = Logger.getLogger(MyWebSocketClient.class);
 
  public MyWebSocketClient(URI serverUri) {
     super(serverUri);
  }

  @Override
  public void onOpen(ServerHandshake arg0) {
    // TODO Auto-generated method stub
    logger.info("------ MyWebSocket onOpen ------");
  }

  @Override
  public void onClose(int arg0, String arg1, boolean arg2) {
     // TODO Auto-generated method stub
     logger.info("------ MyWebSocket onClose ------");
  }

  @Override
  public void onError(Exception arg0) {
     // TODO Auto-generated method stub
     logger.info("------ MyWebSocket onError ------");
  }

  @Override
  public void onMessage(String arg0) {
     // TODO Auto-generated method stub
     logger.info("-------- 接收到服务端数据: " + arg0 + "--------");
  }
}

MyTest 测试类

public class MyTest{

  public static void main(String[] arg0){
    // 此处的WebSocket服务端URI,上面服务端第2点有详细说明     MyWebSocketClient myClient
= new MyWebSocketClient("此处为websocket服务端URI");     // 往websocket服务端发送数据     myClient.send("此为要发送的数据内容");   } }