首页 新闻 会员 周边 捐助

javaweb简单websocket报错404

0
悬赏园豆:20 [已关闭问题] 关闭于 2019-05-10 15:13

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**

  • 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");
    }
    }

<!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://127.0.0.1:8080/aaa/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>

问题补充:

tomcat:D:\apache-tomcat-7.0.88

CXL123的主页 CXL123 | 初学一级 | 园豆:90
提问于:2019-05-05 17:23
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册