分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

websocket client in html

发布时间:2023-09-06 01:20责任编辑:苏小强关键词:websocket
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
???<meta charset="UTF-8"/>
???<title>广播式WebSocket</title>
???<script src="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"></script>
???<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
???<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #e80b0a;">Sorry,no supporting WebSocket</h2></noscript>
<div>
???<div>
???????<button id="connect" onclick="connect();">连接</button>
???????<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
???</div>

???<div id="conversationDiv">
???????<label>输入你的名字</label><input type="text" id="name"/>
???????<button id="sendName" onclick="sendName();">发送</button>
???????<p id="response"></p>
???</div>

???<div id="message"></div>
</div>
<script type="text/javascript">
???var stompClient = null;
???function setConnected(connected) {
???????document.getElementById("connect").disabled = connected;
???????document.getElementById("disconnect").disabled = !connected;
???????document.getElementById("conversationDiv").style.visibility = connected ? ‘visible‘ : ‘hidden‘;
// ???????$("#connect").disabled = connected;
// ???????$("#disconnect").disabled = !connected;
???????$("#response").html();
???}
???function connect() {
???????var socket = new SockJS(‘localhost:8080/endpointSang‘);
???????stompClient = Stomp.over(socket);
???????stompClient.connect({}, function (frame) {
???????????setConnected(true);
???????????console.log(‘Connected:‘ + frame);
???????????stompClient.subscribe(‘/topic/getResponse‘, function (response) {
???????????????//showResponse(response.body);
???????????????setMessageInnerHTML(response.body)
???????????})
???????});
???}
???function disconnect() {
???????if (stompClient != null) {
???????????stompClient.disconnect();
???????}
???????setConnected(false);
???????console.log(‘Disconnected‘);
???}
???function sendName() {
???????var name = $(‘#name‘).val();
???????console.log(‘name:‘ + name);
???????stompClient.send("/welcome", {}, JSON.stringify({‘name‘: name}));
???}
???function showResponse(message) {
???????$("#response").html(message);
???}

???//将消息显示在网页上
???function setMessageInnerHTML(innerHTML) {
???????document.getElementById(‘message‘).innerHTML += innerHTML + ‘<br/>‘;
???}
</script>
</body>
</html>

websocket client in html

原文地址:http://www.cnblogs.com/goldengallo/p/7747457.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved