【Java】WebSocket实例

本文详细介绍WebSocket的客户端和服务端实现过程,包括使用Java和SpringMVC搭建WebSocket服务,以及JavaScript前端如何连接并通信。同时,提供了从依赖添加到前端页面展示的完整示例。

一、DEMO实现

(1)客户端实现。

<button onclick="sendMsg()">发送消息</button>
<script type="text/javascript">
	var webSocket = new WebSocket('ws://localhost:8080/TestWebSocket/websocket/' + 'huangwei');
	
	var sendMsg = ()=>{
		webSocket.send("I'm Client");
	};
	
	webSocket.onerror = ()=>{
		console.log('WebSocket连接出错');
	}
	
	webSocket.onopen = ()=>{
		console.log('WebSocket连接已打开');
	}
	
	webSocket.onmessage = (event)=>{
		console.log('接收消息: ' + event.data);
	}
	
	webSocket.onclose = ()=>{
		console.log('Server已关闭');
	}
	
</script>

(2)服务端实现。

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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

@ServerEndpoint("/websocket/{username}")
public class WebSocketServer {
	
	private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<String, WebSocketServer>();
	
	private Session session;
	
	private String username;
	
	@OnOpen
	public void onOpen(@PathParam("username") String username, Session session) {
		this.username = username;
		this.session = session;
		clients.put("username", this);
		System.out.println("client已连接");
	}
	
	@OnMessage
	public void onMessage(String msg) {
		System.out.println("接收消息: " + msg);
		for(WebSocketServer client : clients.values()) {
			client.session.getAsyncRemote().sendText("I'm Server");
		}
	}
	
	@OnClose
	public void onClose() {
		clients.remove(username);
	}

	@OnError
	public void onError(Throwable err) {
		System.out.println("WebSocket出错");
	}
	
}

二、SpringMVC实现

(1)添加所需依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-websocket</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-messaging</artifactId>
</dependency>

(2)编写WebSocket协议处理器


import org.springframework.web.socket.*;

import java.util.concurrent.ConcurrentHashMap;

public class MyWebSocketHandler implements WebSocketHandler {

    private static ConcurrentHashMap<String, WebSocketSession> users = new ConcurrentHashMap<String, WebSocketSession>();

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        users.put(webSocketSession.getId(), webSocketSession);
        System.out.println("[+]连接已建立");
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        System.out.println("信息: " + webSocketMessage.getPayload().toString());
        webSocketSession.sendMessage(new TextMessage("I'm Server"));
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        users.remove(webSocketSession);
        webSocketSession.close(closeStatus);
    }

    //是否支持分包
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

(3)配置websocket映射和处理类

<bean id="webSocketHandler" class="cn.edu.yau.controller.MyWebSocketHandler"></bean>

<websocket:handlers>
    <websocket:mapping path="/ws/" handler="webSocketHandler"/>
    <!--握手Interceptor,拦截部分WebSocket通信-->
    <!--
    <websocket:handshake-interceptors>
        <bean class=""></bean4.>
    </websocket:handshake-interceptors>
    -->
</websocket:handlers>

<!--注册sockJS,sockJS是Spring提供的对不能使用WebSocket协议的客户端提供一种模拟-->
<websocket:handlers>
    <websocket:mapping path="/sockjs/ws/" handler="webSocketHandler"/>
</websocket:handlers>

(4) 前端页面

<button onclick="sendMsg()">发送消息</button>
<script type="text/javascript">
	var webSocket = new WebSocket("ws://localhost:8080/ksxt/ws/");
	
	var sendMsg = ()=>{
		webSocket.send("I'm Client");
	};
	
	webSocket.onerror = ()=>{
		console.log('WebSocket连接出错');
	}
	
	webSocket.onopen = ()=>{
		console.log('WebSocket连接已打开');
	}
	
	webSocket.onmessage = (event)=>{
		console.log('接收消息: ' + event.data);
	}
	
	webSocket.onclose = ()=>{
		console.log('Server已关闭');
	}
	
	
</script>
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值