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

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

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

服务端:

1、添加Jar包依赖:

<dependency>
  <groupId>Javax.websocket</groupId>
  <artifactId>javax.websocket-api</artifactId>
  <version>1.1</version>
  <scope>provided</scope>
</dependency>

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

3、实现onOpen、onClose、onMessage、onError等方法

实例代码:

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<String, MyWebSocketServer> 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<MyWebSocketServer> getValues(){
        return webSocketMap.values();
    }
}

客户端:

1、添加Jar包依赖:

<dependency>
  <groupId>org.java-websocket</groupId>
  <artifactId>Java-WebSocket</artifactId>
  <version>1.3.8</version>
</dependency>

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

3、实现构造器,重写onOpen、onClose、onMessage、onError等方法

实例代码:

MyWebSocketClient 类

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f2717ed1f4cc7c3ba6e49440ebf1b3f4.html