Websocket的使用(javax.websocket版本)

1.服务端

1.1.pom.xml

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
</dependency>

1.2.WebSocketServer

使用@ServerEndpoint注解

package com.fracong.test.server;

import javax.websocket.CloseReason;
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("/test/ws/{user_name}")
public class WebSocketServer {
    
    
	private String userName;
	private Session session;
    
    /**
     * To execute when it connected
     * @param user
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("user_name") String userName, Session session) {
    
    
    	this.userName = userName;
    	this.session = session;
        WebSocketUtils.serverClients.put(session.getId(), this);
    }

    /**
     * To execute when get message
     * @param message
     * @param session
     * @return
     */
    @OnMessage
    public String onMessage(String message, Session session) {
    
    
        System.out.println(this.userName + ":" + message);
        return this.userName + ":" + message;
    }

    /**
     * To execute when closed the connector
     * @param session
     * @param closeReason
     */
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
    
    
    	WebSocketUtils.serverClients.remove(session.getId());
        System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }

    /**
     * To execute when an error occurs
     * @param t
     */
    @OnError
    public void onError(Throwable t) {
    
    
        t.printStackTrace();
    }

	public String getUserName() {
    
    
		return userName;
	}

	public void setUserName(String userName) {
    
    
		this.userName = userName;
	}

	public Session getSession() {
    
    
		return session;
	}

	public void setSession(Session session) {
    
    
		this.session = session;
	}
}

1.3.WebSocketUtils

使用WebSocketUtils来进行message的发送。

package com.fracong.test.server;

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

import javax.websocket.Session;

public class WebSocketUtils {
    
    
	public static final Map<String, MpsWsServer> serverClients = new ConcurrentHashMap<String, MpsWsServer>();
	
	public static Boolean sendMessageByUser(String userName, String text) {
    
    
		try {
    
    
			for (MpsWsServer server : serverClients.values()) {
    
    
				if(userName.equals(server.getUserName()) && server.getSession() != null
						&& server.getSession().isOpen()){
    
    
					server.getSession().getAsyncRemote().sendText(text);
				}
			}
			
		} catch (Exception e) {
    
    
		
		}
		return false;
	}
	
	public static void sendAllMessage(String text) {
    
    
		for (MpsWsServer server : serverClients.values()) {
    
    
			if (server.getSession() != null && server.getSession().isOpen()) {
    
    
				server.getSession().getAsyncRemote().sendText(text);
			}
		}
	}
}

2.客户端

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebSocket Client</title>

<script type="text/javascript" language="javascript">
	var websocket;

	function init()
	{
     
     
		output = document.getElementById("output");
	}

	function send()
	{
     
     
		var wsUri = "ws://localhost:8080/test-demo/test/ws/demo";
		writeToScreen("Connecting to : "+ wsUri);
		websocket = new WebSocket(wsUri);
		websocket.onopen = function(evt)
		{
     
     
			writeToScreen("Connect Success!");
			doSend(document.getElementById("textID").value);
		};
		websocket.onmessage = function(evt)
		{
     
     
			writeToScreen("Received Message: "+ evt.data);
			websocket.close();
		};
		websocket.onerror = function (evt)
		{
     
     
			writeToScreen('<span style="color:red;">ERROR:</span>'+evt.data);
		};
	}
	function doSend(message)
	{
     
     
		websocket.send(message);
		writeToScreen("Send Message : "+message);
	}

	function writeToScreen(message)
	{
     
     
		var pre = document.createElement("p");
		pre.style.wordWrap = "break-word";
		pre.innerHTML = message;
		output.appendChild(pre)
	}

	window.addEventListener("load", init, false);

</script>
</head>
<body>
	<h1>WebSocket Client</h1>

	<div style="text-align:left;">
	<form action="">
		<input onclick="send()" value="Send Message" type="button">
		<input id="textID" name="message" value="Hello Web Socket" type="text">
		<br>
	</form>

	</div>
	<div id="output"></div>
</body>
</html>

如果使用长链接,那么websocket.close()不需要进行关闭,同时也不需要每次点击send的时候,new一个新的WebSocket

猜你喜欢

转载自blog.csdn.net/m0_37356874/article/details/108055621
今日推荐