资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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 clients = new ConcurrentHashMap(); 
 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 getClients() { 
  return clients; 
 } 
} 

网站栏目:java实现websocket的两种方式实例详解-创新互联
URL分享:http://cdkjz.cn/article/cedgce.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220