WebSocket-java实现
阅读原文时间:2023年07月11日阅读:2

一、所需jar

二、创建websocket.jsp(注意此页面链接,需要链接到自己的服务)

<%@ page language="java" import="java.util.\*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

Web Socket Client

Send :

Receive :



三、创建服务类WebSocketServer.java

package com.sh.test;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.tagext.TryCatchFinally;
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;

import org.springframework.asm.commons.TryCatchBlockSorter;

/**
* WebSocket服务
*
*/
@ServerEndpoint("/ws")
public class WebSocketServer{

 private static List<WebSocketServer> wslist = new ArrayList<WebSocketServer>();

 private Session session;

 public WebSocketServer() {  
 }  
 /\*\*  
  \* 连接后执行  
  \* @param session  
  \*/  
 @OnOpen  
 public void onOpen(Session session) {  
     System.out.println("连接开启");  
     String str = session.getQueryString();//获取开启后的参数 链接?后面的字符串  
     wslist.add(this);

     this.session = session;  
 }

 /\*\*  
  \* 接到消息执行  
  \* @param session  
  \* @param msg  
  \*/  
 @OnMessage  
 public void message(Session session, String msg) {  
     for(WebSocketServer wss : this.wslist) {//可循环对所有人广播,也可单独对一人广播  
         if(wss.session != null && wss.session.isOpen()) {  
             wss.session.getAsyncRemote().sendText(wss.session.getId()+" send msg "+msg);  
         }  
     }  
 }

 /\*\*  
  \* 关闭后执行执行  
  \* @param session  
  \*/  
 @OnClose  
 public void onClose(Session session) {  
     System.out.println("连接关闭");  
     if(wslist.contains(this)) {  
         wslist.remove(this);  
     }  
 }  
 /\*\*  
  \* 关闭浏览器后执行  
  \* @param t  
  \*/  
 @OnError  
 public void onError(Throwable t) {  
     if(wslist.contains(this)) {  
         wslist.remove(this);  
     }  
 }

}

四、创建测试方法TestController.java

package com.sh.test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {
private void TestController() {}
@RequestMapping(value = "/ws", method = RequestMethod.GET)
public String ws(HttpServletRequest request, HttpServletResponse response) {
return "/websocket";
}

}

五、使用TomCat运行项目,即可通讯

http://192.168.1.168:8080/wstest/ws

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章