java WebSocket Demo

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

java WebSocket Demo_第1张图片

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

 

你可能感兴趣的:(java WebSocket Demo)