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;
    }
}

@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();
    }
}

编写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 + "--------");
    }



}

编写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

    }
}
  • 4
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个简单的 Spring Boot WebSocket 入门 demo: 1. 首先,在 pom.xml 文件中引入 `spring-boot-starter-websocket` 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建一个简单WebSocket 处理器: ```java @Component public class WebSocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); session.sendMessage(new TextMessage("连接成功!")); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession webSocketSession : sessions) { webSocketSession.sendMessage(new TextMessage("客户端说:" + message.getPayload())); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } } ``` 3. 创建 WebSocket 配置类: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/ws").setAllowedOrigins("*"); } } ``` 4. 编写一个简单的页面来测试 WebSocket: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket</title> </head> <body> <h1>WebSocket Demo</h1> <div> <input type="text" id="input"/> <button onclick="send()">发送</button> </div> <div id="output"></div> <script> var socket = new WebSocket("ws://localhost:8080/ws"); socket.onmessage = function(event) { var output = document.getElementById("output"); output.innerHTML += "<p>" + event.data + "</p>"; }; function send() { var input = document.getElementById("input"); socket.send(input.value); input.value = ""; } </script> </body> </html> ``` 5. 运行程序,访问 http://localhost:8080/index.html,打开浏览器控制台,输入命令 `socket.send("Hello, WebSocket!")`,即可看到页面上显示出 "客户端说:Hello, WebSocket!"。 希望这个 demo 能帮助到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值