JSP与WebSocket通信实践

发布时间:2024-11-13 15:31:58 作者:小樊
来源:亿速云 阅读:78

JSP(JavaServer Pages)是一种基于服务器的用户界面组件框架,用于生成动态网页内容。WebSocket是一种网络通信协议,它允许在单个TCP连接上进行全双工通信。JSP与WebSocket通信实践是指将JSP用于生成网页内容,同时使用WebSocket实现实时数据交互。

以下是一个简单的JSP与WebSocket通信实践示例:

  1. 创建一个WebSocket服务器端类(Server.java):
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/websocket")
public class Server {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Client connected: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message from client: " + message);
        try {
            session.getBasicRemote().sendText("Message received: " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Client disconnected: " + session.getId());
    }

    @OnError
    public void onError(Throwable error) {
        System.out.println("Error occurred: " + error.getMessage());
    }
}
  1. 创建一个WebSocket客户端类(Client.java):
import javax.websocket.*;
import java.io.IOException;

@ClientEndpoint
public class Client {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to server");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received message from server: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Disconnected from server");
    }

    @OnError
    public void onError(Throwable error) {
        System.out.println("Error occurred: " + error.getMessage());
    }

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(Client.class, new URI("ws://localhost:8080/websocket"));

            Client client = new Client();
            client.sendMessage("Hello, WebSocket!");

            Thread.sleep(1000);
            container.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. 创建一个JSP页面(index.jsp):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Communication Example</title>
</head>
<body>
    <h1>WebSocket Communication Example</h1>
    <input type="text" id="messageInput" placeholder="Type your message here">
    <button onclick="sendMessage()">Send</button>
    <div id="messages"></div>

    <script>
        function sendMessage() {
            var input = document.getElementById("messageInput");
            var message = input.value;
            var ws = new WebSocket("ws://localhost:8080/websocket");
            ws.send(message);
            input.value = "";
        }

        var ws = new WebSocket("ws://localhost:8080/websocket");
        ws.onmessage = function(event) {
            var messagesDiv = document.getElementById("messages");
            var newMessage = document.createElement("p");
            newMessage.textContent = event.data;
            messagesDiv.appendChild(newMessage);
        };
        ws.onclose = function() {
            console.log("Disconnected from server");
        };
        ws.onerror = function(error) {
            console.error("Error occurred: " + error);
        };
    </script>
</body>
</html>
  1. 部署WebSocket服务器端类到Java Web应用服务器(如Tomcat),并启动服务器。

  2. 在浏览器中打开JSP页面(index.jsp),输入消息并点击发送按钮,观察浏览器控制台和服务器端的输出,可以看到实时通信的实现。

推荐阅读:
  1. JSP增删改查实例代码分析
  2. Java SpringBoot整合JSP和MyBatis的方法是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jsp

上一篇:JSP页面静态资源优化

下一篇:JSP框架的维护策略

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》