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

服务端:

 1、添加Jar包依赖:


  javax.websocket
  javax.websocket-api
  1.1
  provided

 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 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包依赖:


  org.java-websocket
  Java-WebSocket
  1.3.8

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

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

   

实例代码:

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){
    MyWebSocketClient myClient = new MyWebSocketClient("此处为websocket服务端URI");
    // 往websocket服务端发送数据
    myClient.send("此为要发送的数据内容");
  }

}

WebSocketConfig.java

package com.ruoyi.web.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 开启WebSocket支持
 * @author zhengkai
 */
@Configuration  
public class WebSocketConfig {  
	
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
  
} 

 

你可能感兴趣的:(用JAVA实现WebSocket客户端与服务端)