聊天的实现

本案例是用IDEA创建的maven的web项目


步骤一:在pom.xml文件中导入依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.qf</groupId>
  <artifactId>websocketDemo1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>websocketDemo1 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
      <dependency>
          <groupId>javax.websocket</groupId>
          <artifactId>javax.websocket-api</artifactId>
          <version>1.1</version>
      </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.38</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>websocketDemo1</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


步骤二:创建处理交互信息的类

第一个类:MessageController

package com.qf.controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * 2019/10/4
 * Administrator
 * websocketDemo1
 * 面向对象面向君  不负代码不负卿
 */
@ServerEndpoint("/servlet/pushMessage")
public class MessageController {
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    /**
     * 连接建立成功调用的方法
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("有新连接加入!");
    }
    /** * 连接关闭调用的方法     */
    @OnClose
    public void onClose() {
        System.out.println("有一连接关闭!");
    }
    //接受客户端传递来的内容
    @OnMessage
    public void onMessage (String txt, Session session) {
        System.out.println("onMessage: " + txt.toUpperCase());
        sendMessage(txt.toUpperCase());
    }
    /**     * 发生错误时调用    *
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误"+error);
    }
    /**     * 发送消息到客户端     *
     */
    public void sendMessage(String message) {
//        this.session.getBasicRemote().sendText(message);
        this.session.getAsyncRemote().sendText(message);//
    }

}

第一个类:PushWebSocketServlet

package com.qf.controller;

import com.alibaba.fastjson.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * 2019/10/4
 * Administrator
 * websocketDemo1
 * 面向对象面向君  不负代码不负卿
 */
@ServerEndpoint("/servlet/{name}")
public class PushWebSocketServlet {
    private String name;//记录当前websocke是谁
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;//链接,记录当前链接
    //存储多个用户的信息
    private static Map<String,Session> clients = new HashMap<>();
    /**
     * 连接建立成功调用的方法
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据     */
    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name) {
        this.session = session;
        this.name = name;
        clients.put(name,session);
        System.out.println("有新连接加入!");
    }
    /** * 连接关闭调用的方法     */
    @OnClose
    public void onClose() {
        System.out.println("有一连接关闭!" );
    }
    //接受客户端传递来的内容,处理消息,根据业务编写逻辑。
    //两个人聊天,收到消息后,看看是发给谁的。然后转发给另外一个人。
    // 如何判断另外一个接受者?服务端约定客户端怎么发?格式{to:zhansan,message:hello}
    @OnMessage
    public void onMessage (String txt, Session session) {
        System.out.println("onMessage: " + txt.toUpperCase());
        //首先解析发过来的内容,找到目标者
        JSONObject jsonObject = JSONObject.parseObject(txt);
        String to =jsonObject.getString("to");
        String toMessage = jsonObject.getString("msg");
        Session sessionTarget = clients.get(to);
        //根据目标接受者,找到它的session链接
        if(sessionTarget !=null) {
            if(sessionTarget.isOpen()){
                //得到链接的另外一端,然后发送消息
                sessionTarget.getAsyncRemote().sendText(toMessage);
            }
        }else {
            //正常来说需要缓存这个消息,这里直接返回给发送方
            session.getAsyncRemote().sendText("对方不在线");
        }
    }
    /**     * 发生错误时调用    *     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误"+error);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Session getSession() {
        return session;
    }
    public void setSession(Session session) {
        this.session = session;
    }
}


步骤三:创建发送请求的页面

第一个页面:index.jsp

<%@page pageEncoding="UTF-8" language="java" contentType="text/html;charset=utf-8" %>
<html>
<h1>Echo Test</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
    //指向服务端的接口地址
    var websocket=new WebSocket('ws://localhost:8080/servlet/pushMessage');
    //建立连接
    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);
        document.getElementById("recv").innerHTML=e.data;
    }
</script>
</body>

</html>

第二个页面:online2.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/10/4
  Time: 16:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Echo Test</h1>
用户名:<input id="name" name="name" type="text" />
<button onclick="myconn()">链接</button><br>
接受者名称:<input id="to" name="to" type="text" /><br>
发送内容:<input id="msg" name="msg" type="text" />
<button id="sendBtn" onclick="sendMsg()">发送</button>
<div id="recv"></div>
<script type="text/javascript">
    var websocket=null;
    function myconn() {
        var name = document.getElementById("name").value;
        websocket=new WebSocket('ws://localhost:8080/servlet/'+name);
        //建立连接
        websocket.onopen=function(){
            console.log('websocket open');
            document.getElementById("recv").innerHTML="建立链接了";
        }
        //关闭连接
        websocket.onclose==function(){
            console.log('websocket close');
        }
        //客户端接收数据触发
        websocket.onmessage=function(e){
            console.log(e.data);
            showMessage(e.data);
        }
    }
    function showMessage(str){
        document.getElementById("recv").innerHTML=str;
    }
    //给服务端发送数据
    function sendMsg() {
        var toUser = document.getElementById("to").value;
        var toMsg = document.getElementById("msg").value;
        if(websocket!=null){
//发送的json数据
            var msg = '{"to":"'+toUser+'","msg":"'+toMsg+'"}';
            websocket.send(msg);
        }
    }
</script>
</body>

</html>

注释:在tomcat启动时,访问online2.jsp页面即可





本次案例结构图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值