websocket 使用demo (2)

web servlet方式

html

<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket demo</title>
<style>
body {padding: 40px;}
#outputPanel {margin: 10px;padding:10px;background: #eee;border: 1px solid #000;min-height: 300px;}
</style>
</head>
<body>
<input type="text" id="messagebox" size="60" />
<input type="button" id="buttonSend" value="Send Message" />
<input type="button" id="buttonConnect" value="Connect to server" />
<input type="button" id="buttonClose" value="Disconnect" />
<br>
<!-- <% out.println("Session ID = " + session.getId()); %> -->
<div id="outputPanel"></div>
</body>
<script type="text/javascript">
	var infoPanel = document.getElementById('outputPanel'); // 输出结果面板
	var textBox = document.getElementById('messagebox');	// 消息输入框
	var sendButton = document.getElementById('buttonSend');	// 发送消息按钮
	var connButton = document.getElementById('buttonConnect');// 建立连接按钮
	var discButton = document.getElementById('buttonClose');// 断开连接按钮
	// 控制台输出对象
	var console = {log : function(text) {infoPanel.innerHTML += text + "<br>";}};
	// WebSocket演示对象
	var demo = {
		socket : null, 	// WebSocket连接对象
		host : 'ws://localhost:8080/a/websocket/say',		// WebSocket连接 url
		connect : function() { 	// 连接服务器
			window.WebSocket = window.WebSocket || window.MozWebSocket;
			if (!window.WebSocket) {	// 检测浏览器支持
				console.log('Error: WebSocket is not supported .');
				return;
			}
			this.socket = new WebSocket(this.host); // 创建连接并注册响应函数
			this.socket.onopen = function(){console.log("websocket is opened .");};
			this.socket.onmessage = function(message) {console.log(message.data);};
			this.socket.onclose = function(){
				console.log("websocket is closed .");
				demo.socket = null; // 清理
			};
		},
		send : function(message) {	// 发送消息方法
			if (this.socket) {
				this.socket.send(message);
				return true;
			}
			console.log('please connect to the server first !!!');
			return false;
		}
	};
	// 初始化WebSocket连接 url
	//demo.host=(window.location.protocol == 'http:') ? 'ws://localhost:8080' : 'wss://localhost:8080' ;
	//demo.host =  'ws://localhost:8080/a/websocket/say';
	// 初始化按钮点击事件函数
	sendButton.onclick = function() {
		var message = textBox.value;
		if (!message) return;
		if (!demo.send(message)) return;
		textBox.value = '';
	};
	connButton.onclick = function() {
		if (!demo.socket) {
			demo.connect();
		}
			
		else console.log('websocket already exists .');
	};
	discButton.onclick = function() {
		if (demo.socket) demo.socket.close();
		else  console.log('websocket is not found .');
	};
</script>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>websocket demo</display-name>
    <servlet>
        <servlet-name>wsHello</servlet-name>
        <servlet-class>websocket.HelloWebSocketServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>wsHello</servlet-name>
        <url-pattern>/websocket/say</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

java

package websocket;

import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

public class HelloWebSocketServlet extends WebSocketServlet {
	private static final long serialVersionUID = 1L;

	private final AtomicInteger connectionIds = new AtomicInteger(0);
	@Override
	protected StreamInbound createWebSocketInbound(String arg0,
			HttpServletRequest request) {
		return new HelloMessageInbound(connectionIds.getAndIncrement(), request
				.getSession().getId());
	}
}

package websocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.CharBuffer;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WsOutbound;

public class HelloMessageInbound extends StreamInbound {

	private String WS_NAME;
	private final String FORMAT = "%s : %s";
	private final String PREFIX = "ws_";
	private String sessionId = "";

	public HelloMessageInbound(int id, String _sessionId) {
		this.WS_NAME = PREFIX + id;
		this.sessionId = _sessionId;
	}

	@Override
	protected void onTextData(Reader reader) throws IOException {
		char[] chArr = new char[1024];
		int len = reader.read(chArr);
		send(String.copyValueOf(chArr, 0, len));
	}

	@Override
	protected void onClose(int status) {
		System.out.println(String.format(FORMAT, WS_NAME, "closing ......"));
		super.onClose(status);
	}

	@Override
	protected void onOpen(WsOutbound outbound) {
		super.onOpen(outbound);
		try {
			send("hello, my name is " + WS_NAME);
			send("session id = " + this.sessionId);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void send(String message) throws IOException {
		message = String.format(FORMAT, WS_NAME, message);
		System.out.println(message);
		getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
	}

	@Override
	protected void onBinaryData(InputStream arg0) throws IOException {
	}
}



好的,以下是一个使用示例,演示如何使用我们之前提供的 WebSocket 代码: ```html <!-- 在 HTML 中引入 WebSocket JavaScript 文件 --> <script src="websocket.js"></script> <!-- 在 JavaScript 中连接到 WebSocket 服务器 --> <script> // 连接到 WebSocket 服务器 connect(); // 发送消息到服务器 document.getElementById("send-button").addEventListener("click", function() { const message = document.getElementById("message-input").value; send(message); }); // 关闭 WebSocket 连接 document.getElementById("close-button").addEventListener("click", function() { close(); }); </script> <!-- 在 HTML 中添加一些控件,以便发送消息和关闭 WebSocket 连接 --> <input type="text" id="message-input"> <button id="send-button">Send</button> <button id="close-button">Close</button> ``` 在此示例中,我们首先引入 WebSocket JavaScript 文件。然后,在 JavaScript 中,我们调用 `connect()` 函数连接到 WebSocket 服务器。我们还为“发送”和“关闭”按钮添加了点击事件监听器,以便在用户点击这些按钮时发送消息或关闭 WebSocket 连接。 最后,我们在 HTML 中添加了一个文本输入框和两个按钮,以便发送消息或关闭 WebSocket 连接。 请注意,您需要将 `websocket.js` 替换为实际的 WebSocket JavaScript 文件的名称,并将 WebSocket 服务器的 URL 替换为实际的 URL。 希望这个示例可以帮助您开始使用 WebSocket。如果您需要更多帮助,请告诉我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值