Tomcat8实现WebSocket

Tomcat8实现WebSocket

api

引入Tomcat下websocket-api.jar

后台服务端代码

package com.fh.controller.app.socket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

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


@ServerEndpoint("/websocket")
public class WebsocketService {
	private static int online = 0;
	private static CopyOnWriteArraySet<WebsocketService> websocketServices = new CopyOnWriteArraySet<WebsocketService>();
	private Session session;
	
	@OnOpen
	public void onOpen(Session session){
		this.session = session;
		websocketServices.add(this);
		addOnlineCount();
		System.out.println("有新的连接加入,当前在线人数为"+getOnlineCount());
	}
	
	@OnClose
	public void onClose(){
		websocketServices.remove(this);
		subOnline();
		System.out.println("有一个连接关闭,当前在线人数为"+getOnlineCount());
	}
	
	public static synchronized void subOnline() {
		WebsocketService.online--;
	}

	public static synchronized int getOnlineCount() {
		return online;
	}
	public static synchronized void addOnlineCount() {
		WebsocketService.online++;
	}

	@OnMessage
	public void onMessage(String message,Session session){
		System.out.println("来自客户端的消息:"+message);
		String id = session.getId();
		System.out.println(id);
		for(WebsocketService service:websocketServices){
			try {
				Session strSession = service.session;
				System.out.println(strSession.getId());
				/*if(id.equals(strSession.getId())){
					continue;
				}*/
				/*if(id.equals(service.getId(service))){
					
				}*/
				service.sendMessage(message);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}
	
	public void sendMessage(String message) throws IOException{
		this.session.getBasicRemote().sendText(message);
	}
	
	@OnError
	public void onError(Session session,Throwable e){
		System.out.println("发生错误");
		e.printStackTrace();
	}
	
}

前段页面

<!DOCTYPE html>
<html>
	<head>
	     <title>websocket</title>
	     <script type="text/javascript">
	          var websocket = null;
	          if('WebSocket' in window){
	        	  websocket = new WebSocket("ws://localhost:8080/Auxiliary/websocket");
	          }else{
	        	  alert("当前浏览器不支持WebSocket");
	          }
	          
	          function send(){
	        	  var message = document.getElementById("message").value;
	        	  websocket.send(message);
	          }
	          
	          function showMessage(message){
	        	  document.getElementById("message-list").innerHTML += message+"<br/>";
	          }
	          
	          function closeWebsocket(){
	        	  websocket.close();
	          }
	          websocket.onerror = function(){
	        	  showMessage("连接发生错误");
	          }
	          
	          websocket.onopen = function(){
	        	  showMessage("websocket连接成功");
	          }
	          
	          websocket.onmessage = function(event){
	        	  showMessage(event.data);
	          }
	          
	          websocket.onclose = function(){
	        	  showMessage("websocket连接关闭");
	          }
	          
	          websocket.onbeforeupload = function(){
	        	  closeWebsocket();
	          }
	          
	          
	     </script>
	</head>
	<body>
	    <h2>chatroom with websocket</h2>
	    <div id="container">
	        <div>
		        <input type="text" name="message" id="message" placeholder="hello,websocket"/>
		        <input type="button" value="send" onclick="send()"/>
	        </div>
	        <div id="message-list">
	        
	        </div>
	    </div>
	    
	</body>
</html>

注意:websocket跨域和URL拦截问题

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值