我的环境:jdk1.8.0_131

                maven:3.5.0

                tomcat:8.5.23(据说要在1.7.49以上才支持websocket)

在maven配置文件中添加jar包依赖

    <dependency>     
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>8.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>


在index写入测试代码

<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
</head>
<body>
<h1>Echo Test</h1>
<input type="text" id="sendTxt"/>
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
    var websocket=new WebSocket("ws://localhost:8080/websocket");
    function showMessage(str,type) {
        var div=document.createElement('div');
        div.innerHTML=str;
        if(type=="enter"){
            div.style.color="blue";
        }else if(type=="leave"){
            div.style.color="red";
        }
        document.body.appendChild(div);
    }
    websocket.onopen=function(){
        console.log('websocket open');
        document.getElementById("sendBtn").onclick=function(){
            var txt=document.getElementById("sendTxt").value;
            if(txt){
                websocket.send(txt);
            }
        }
    }
    websocket.onclose=function(){
        console.log('websocket close');
    }
    websocket.onmessage=function(e){
        console.log(e.data);
        var mes=JSON.parse(e.data);
        showMessage(mes.data,mes.type);
    }

</script>
</body>
</html>

重点:在测试类WebSocketTest中编写

package cn.labmem;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
/**

  • Created by 刘天予

  • 2017/11/20 1:17
    */
    @ServerEndpoint("/websocket")
    public class WebSocketTest {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int clientCount = 0;
    private String nickname;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**

    • 连接建立成功调用的方法
    • @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
      */
      @OnOpen
      public void onOpen(Session session){
      this.session = session;
      webSocketSet.add(this); //加入set中
      addclientCount();
      nickname="user"+getclientCount();
      message me=new message();
      me.setType("enter");
      me.setData(nickname+"加入聊天");
      //使用JSONObject将Java对象转化为json字符串
      JSONObject json = JSONObject.fromObject(me);
      broadcast(json.toString());
      }

    /**

    • 连接关闭调用的方法
      */
      @OnClose
      public void onClose(){
      webSocketSet.remove(this); //从set中删除
      message me=new message();
      me.setType("leave");
      me.setData(nickname+"离开");
      //使用JSONObject将Java对象转化为json字符串
      JSONObject json = JSONObject.fromObject(me);
      broadcast(json.toString());
      }

    /**

    • 收到客户端消息后调用的方法
    • @param message 客户端发送过来的消息
    • @param session 可选的参数
      */
      @OnMessage
      public void onMessage(String message, Session session) {
      message me=new message();
      me.setType("message");
      me.setData(nickname+"说:"+message);
      //使用JSONObject将Java对象转化为json字符串
      JSONObject json = JSONObject.fromObject(me);
      broadcast(json.toString());
      }

    /**

    • 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
    • @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 getclientCount(){return clientCount;}
    public static synchronized void addclientCount(){ clientCount++;}

    /**

    • 群发消息
      */
      public void broadcast(String str){
      for(WebSocketTest item: webSocketSet){
      try {
      item.sendMessage(str);
      } catch (IOException e) {
      e.printStackTrace();
      continue;
      }
      }
      }
      }



简单的JavaWebSocket就完成了

效果图:



有了基础,在基础上盖楼就不是问题了😉