websocket是Html5的一个协议,也就是说距离我们2016年就几年时间,其他原理我就不说了,直接讲例子

一、准备材料:1、一个开发工具必须支持javaEE7的,原因是javaEE6或以下不支持websocket,我是使用的开发工具是myeclipse2015,这里给各位百度云盘

  链接: https://pan.baidu.com/s/1eS3DrPK 密码: 4fe1,里面有破解的工具,很方便

                  2、tomcat8.0以上、JDK7.0以上(这个也许就是websocket是近几年的原因)

二、创建一个web项目,必须选择JavaEE7.0以上(图1-1)

                                图1-1

三、

(1)、jsp代码

复制代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta content="text/html";charset="utf-8">
    <script src="<%=request.getContextPath()%>/js/jquery-2.1.4.min.js" ></script>
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <form>
         <h1>WebSocket送信实例</h1>
         <input type="text" id="message"  disabled="disabled" required>
         <input type="button" onclick="echo()" disabled="disabled" value="提交">
     </form>
  </body>
    <script>
    if (!window.WebSocket && window.MozWebSocket)
        window.WebSocket = window.MozWebSocket;
    if (!window.WebSocket) {
        alert("此浏览器不支持WebSocket");
    }
    //创建WebSocket,location.host获得主机名+端口号
    var ws = new WebSocket("ws://" + location.host + "/websocket/websocket");
    //连接建立后调用的函数
    ws.onopen = function() {
        //将我们的form改变为可以输入的形式
        $("form *").attr("disabled", false);
    }
    //接受服务器传入的数据的处理
    ws.onmessage = function(event) {
        alert(event.data);
    }
    //点击提交按钮后调用的参数
    function echo() {
        ws.send($("#message").val());
    }
</script>
</html>
复制代码

(2)、java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com;
 
import java.io.IOException;
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 MyWebSocket { 
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 
    private static int onlineCount = 0
        
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); 
        
    //与某个客户端的连接会话,需要通过它来给客户端发送数据 
    private Session session; 
        
    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */ 
    @OnOpen 
    public void onOpen(Session session){ 
        this.session = session; 
        webSocketSet.add(this);     //加入set中 
        addOnlineCount();           //在线数加1 
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); 
    
        
    /**
     * 连接关闭调用的方法
     */ 
    @OnClose 
    public void onClose(){ 
        webSocketSet.remove(this);  //从set中删除 
        subOnlineCount();           //在线数减1     
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); 
    
        
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */ 
    @OnMessage 
    public void onMessage(String message, Session session) { 
        System.out.println("来自客户端的消息:" + message); 
            
        //群发消息 
        for(MyWebSocket item: webSocketSet){              
            try
                item.sendMessage(message); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                continue
            
        
    
        
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */ 
    @OnError 
    public void onError(Session session, Throwable error){ 
        System.out.println("发生错误"); 
        error.printStackTrace(); 
    
        
    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */ 
    public void sendMessage(String message) throws IOException{ 
        this.session.getBasicRemote().sendText(message); 
        //this.session.getAsyncRemote().sendText(message); 
    
    
    public static synchronized int getOnlineCount() { 
        return onlineCount; 
    
    
    public static synchronized void addOnlineCount() { 
        MyWebSocket.onlineCount++; 
    
        
    public static synchronized void subOnlineCount() { 
        MyWebSocket.onlineCount--; 
    
}

 

(3).web.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>EchoServlet</servlet-name>
    <servlet-class>com.EchoServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>MyWebSocket</servlet-name>
    <servlet-class>com.MyWebSocket</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>EchoServlet</servlet-name>
    <url-pattern>/servlet/EchoServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>MyWebSocket</servlet-name>
    <url-pattern>/servlet/MyWebSocket</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
复制代码

 相信大家好好体会代码,我也是花了一两个钟才做成这个例子的,然后就立刻给博客友写文章,喜欢和我交流可以加我的博客园

posted on   我是坏男孩  阅读(1609)  评论(2编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示