java实现websocket的两种方式实例详解-创新互联

一、介绍

1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket

创新互联长期为1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为淮上企业提供专业的成都网站建设、网站设计淮上网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制开发。

2.tomcat的方式需要tomcat 7.x,JEE7的支持。

3.spring与websocket整合需要spring 4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟websocket使用

二、方式一:tomcat

使用这种方式无需别的任何配置,只需服务端一个处理类,

 服务器端代码

package com.Socket; 
import java.io.IOException; 
import java.util.Map; 
import java.util.concurrent.ConcurrentHashMap; 
import javax.websocket.*; 
import javax.websocket.server.PathParam; 
import javax.websocket.server.ServerEndpoint; 
import net.sf.json.JSONObject; 
@ServerEndpoint("/websocket/{username}") 
public class WebSocket { 
 private static int onlineCount = 0; 
 private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); 
 private Session session; 
 private String username; 
 @OnOpen 
 public void onOpen(@PathParam("username") String username, Session session) throws IOException { 
  this.username = username; 
  this.session = session; 
  addOnlineCount(); 
  clients.put(username, this); 
  System.out.println("已连接"); 
 } 
 @OnClose 
 public void onClose() throws IOException { 
  clients.remove(username); 
  subOnlineCount(); 
 } 
 @OnMessage 
 public void onMessage(String message) throws IOException { 
  JSONObject jsonTo = JSONObject.fromObject(message); 
  if (!jsonTo.get("To").equals("All")){ 
   sendMessageTo("给一个人", jsonTo.get("To").toString()); 
  }else{ 
   sendMessageAll("给所有人"); 
  } 
 } 
 @OnError 
 public void onError(Session session, Throwable error) { 
  error.printStackTrace(); 
 } 
 public void sendMessageTo(String message, String To) throws IOException { 
  // session.getBasicRemote().sendText(message); 
  //session.getAsyncRemote().sendText(message); 
  for (WebSocket item : clients.values()) { 
   if (item.username.equals(To) ) 
    item.session.getAsyncRemote().sendText(message); 
  } 
 } 
 public void sendMessageAll(String message) throws IOException { 
  for (WebSocket item : clients.values()) { 
   item.session.getAsyncRemote().sendText(message); 
  } 
 } 
 public static synchronized int getOnlineCount() { 
  return onlineCount; 
 } 
 public static synchronized void addOnlineCount() { 
  WebSocket.onlineCount++; 
 } 
 public static synchronized void subOnlineCount() { 
  WebSocket.onlineCount--; 
 } 
 public static synchronized Map<String, WebSocket> getClients() { 
  return clients; 
 } 
} 

网站题目:java实现websocket的两种方式实例详解-创新互联
本文来源:https://www.cdcxhl.com/article24/cedgce.html

成都网站建设公司_创新互联,为您提供网站内链小程序开发微信公众号网站策划品牌网站建设做网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设