⽤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")注
websocket和socket
解,@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.apachemons.lang.StringUtils;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;
@ServerEndpoint(value = "/websocket")
public class MyWebSocketServer {
  private Logger logger = Logger(MyWebSocketServer.class);
  private Session session;
  /**
  * 连接建⽴后触发的⽅法
  */
  @OnOpen
  public void onOpen(Session session){
    this.session = session;
    logger.info("onOpen"+Id());
    WebSocketMapUtil.Id(),this);
  }
  /**
  * 连接关闭后触发的⽅法
  */
  @OnClose
  public void onClose(){
    //从map中删除
    Id());
    logger.info("====== onClose:"+Id()+" ======");
  }
  /**
  * 接收到客户端消息时触发的⽅法
  */
  @OnMessage
  public void onMessage(String params,Session session) throws Exception{
    //获取服务端到客户端的通道
    MyWebSocketServer myWebSocket = (Id());
    logger.info("收到来⾃"+Id()+"的消息"+params);
    String result = "收到来⾃"+Id()+"的消息"+params;
    //返回消息给Web Socket客户端(浏览器)
    myWebSocket.sendMessage(1,”成功!”,result);
  }
  /**
  * 发⽣错误时触发的⽅法
  */
  @OnError
  public void onError(Session session,Throwable error){
    logger.Id()+"连接发⽣错误"+Message());
    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);
BasicRemote().String());
}
}
WebSocketMapUtil ⼯具类
import java.util.Collection;
import urrent.ConcurrentHashMap;
import urrent.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){
(key);
}
public static void remove(String 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 类
import java.URI;
import ine.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(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("此为要发送的数据内容");
  }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。