zoukankan      html  css  js  c++  java
  • java WebSocket Demo

    1、IDEA创建Module,结构如图(Tomcat8.0)

    2、引入jar包:javax.websocket-api.jar

    3、新建WebSocketTest类

    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    
    /**
     * Created by JiaPeng on 2016/2/15.
     */
    @ServerEndpoint("/websocket")
    public class WebSocketTest {
        @OnMessage
        public void onMessage(String message, Session session) throws IOException, InterruptedException {
            System.out.println("Received: " + message);
            session.getBasicRemote().sendText("This is the first server message");
    
            int sendMessages = 0;
            while (sendMessages < 10) {
                Thread.sleep(5000);
                session.getBasicRemote().sendText("This is an intermediate server message. Count: " + sendMessages);
                sendMessages++;
            }
            session.getBasicRemote().sendText("This is the last server message");
        }
    
        @OnOpen
        public void OnOpen() {
            System.out.println("Client connected");
        }
    
        @OnClose
        public void OnClose() {
            System.out.println("Connection closed");
        }
    }
    View Code

    4、index.jsp页面代码

    <!DOCTYPE html>
    <html>
    <head>
        <title>Testing websockets</title>
    </head>
    <body>
    <div>
        <input type="submit" value="Start" onclick="start()" />
    </div>
    <div id="messages"></div>
    <script type="text/javascript">
        var webSocket =
                new WebSocket('ws://localhost:8080/websocket');
    
        webSocket.onerror = function(event) {
            onError(event)
        };
    
        webSocket.onopen = function(event) {
            onOpen(event)
        };
    
        webSocket.onmessage = function(event) {
            onMessage(event)
        };
    
        function onMessage(event) {
            document.getElementById('messages').innerHTML
                    += '<br />' + event.data;
        }
    
        function onOpen(event) {
            document.getElementById('messages').innerHTML
                    = 'Connection established';
        }
    
        function onError(event) {
            alert(event.data);
        }
    
        function start() {
            webSocket.send('hello');
            return false;
        }
    </script>
    </body>
    </html>
    View Code
  • 相关阅读:
    个人网站上线
    从零开始学C++之虚函数与多态(二):纯虚函数、抽象类、虚析构函数
    Triangle
    Hard problem
    [置顶] Android AlarmManager实现不间断轮询服务
    Python学习入门基础教程(learning Python)--5.1 Python下文件处理基本过程
    编程之美 裴波那楔数列
    130712周赛(CF)
    Python学习入门基础教程(learning Python)--5.2 Python读文件基础
    phantomjs
  • 原文地址:https://www.cnblogs.com/hujiapeng/p/5191182.html
Copyright © 2011-2022 走看看