当前位置:   article > 正文

Java-websocket介绍以及简单入门_java websocket

java websocket

websocket是什么

websocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器的全双工通讯-允许服务器主动发起信息个客户端,
websocket’是一种持久协议,http是非持久协议。在websocket出现之前,是通过通过ajax轮询来实现网站实时推送消息给浏览器客户端。轮询是指由浏览器每隔一段时间向服务器发出 HTTP 请求,然后服务器返回最新的数据给客户端。轮询的效率低,非常浪费资源。

websocket和http的区别

HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理,HTTP 协议无法实现服务器主动向客户端发起消息。
WebSocket 只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。

java使用tomcat实现websocket服务端

首先需要引入websocket的jar包,包括 tomcat-websocket.jar和websocket-api.jar,这两个jar包在tomcat7以上版本的lib目录下,将这两个jar包拷贝到项目的lib目录下。
在这里插入图片描述
编写websocketServer类

@ServerEndpoint(value = "/websocket/{oid}")
public class WebsocketDemoServer {
    private Session session;
    private String oid;

    /**
     * * 连接建立后触发的方法
     */
    @OnOpen
    public void onOpen(@PathParam("oid") String oid, Session session) {
        this.session = session;
        this.oid = oid;
        System.out.println("onOpen=====" + oid);
        WebSocketMapUtil.put(oid, session);
    }
    /**
     * * 连接关闭后触发的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        WebSocketMapUtil.remove(this.oid);
        System.out.println("====== onClose:" + this.oid + " ======");
    }
    /**
     * * 接收到客户端消息时触发的方法
     */
    @OnMessage
    public void onMessage(String params, Session session) throws Exception {
        System.out.println("收到来自" + this.oid + "的消息" + params);
        String result = "收到来自" + this.oid + "的消息" + params;
        //返回消息给Web Socket客户端(浏览器)
       session.getBasicRemote().sendText(result);
    }
    /**
     * * 发生错误时触发的方法
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println(session.getId() + "连接发生错误" + error.getMessage());
        error.printStackTrace();
    }


    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getOid() {
        return oid;
    }

    public void setOid(String oid) {
        this.oid = oid;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

@ServerEndpoint注解表示websocket请求url,{oid}用来标识每一个websocket客户端的唯一id。

WebSocketMapUtil类 用来保存websocket客户端和websocket连接的对应关系

public class WebSocketMapUtil {

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

    public static void put(String key, Session session) {
        webSocketMap.put(key, session);
    }

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

    public static void remove(String key) {
        webSocketMap.remove(key);
    }

    public static Collection<Session> getValues() {
        return webSocketMap.values();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

编写websocket客户端MyWebSocketClient类,需要java-websocket-1.5.2jar包

public class MyWebSocketClient extends WebSocketClient {

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

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

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

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

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



}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

编写websocket客户端测试类

public class WebSocketTest {

    public static void main(String[] args) {
        try {

            // 创建WebSocket客户端
            MyWebSocketClient myClient = new MyWebSocketClient(new URI("ws://127.0.0.1:9091/web/websocket/345"));
            // 与服务端建立连接
            myClient.connect();
            while (!myClient.getReadyState().equals(ReadyState.OPEN)) {
                System.out.println("连接中。。。");
                Thread.sleep(1000);
            }
            // 往websocket服务端发送数据
            myClient.send("发送来自websocketClient 345的消息");
            Thread.sleep(1000);
            // 关闭与服务端的连接
            // myClient.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        // write your code here

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/249169
推荐阅读
相关标签
  

闽ICP备14008679号