欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用rabbitmq实现点对点聊天功能

程序员文章站 2022-05-21 14:18:30
...

先上功能实现图

输入登录用户,接受方,用英文逗号隔开,模拟接收用户和发送用户

利用rabbitmq实现点对点聊天功能

分别有三个页面

页面1 发送方:孙悟空,接收方:唐三藏

页面2 发送方:唐三藏,接收方:孙悟空

页面3 发送方 唐三藏,接收方 猪八戒

现在用孙悟空给唐三藏发送消息 

利用rabbitmq实现点对点聊天功能

利用rabbitmq实现点对点聊天功能利用rabbitmq实现点对点聊天功能

可以看到只有唐三藏和孙悟空可以看到对方发送的消息,而猪八戒是看不到的,当然其他人也看不到。就实现了点对点聊天功能。

接下来是代码

pom文件代码如下

<?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.cictec.stomp</groupId>
	<artifactId>rabbitmq</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>rabbitmq</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

 项目结构如下:

利用rabbitmq实现点对点聊天功能

后台的只需要看AliveReceiver类就可以,用于心跳检测,防止连接断开

package com.cictec.stomp.config;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AliveReceiver {
	
    @Autowired
    private AmqpTemplate template;
    
	  @RabbitListener(queues="aliveMsg")    //监听器监听指定的Queue
	    public void processC(String str) {
		  System.out.println("Receive:"+str);
	      template.convertAndSend(str+"onAlive","心跳检测");
	    
	    }
}

前端看inner.html

<html>
<body>

<div id="main" style="width: 400px;height: 400px;background-color: antiquewhite;padding-bottom:20px;">
    <div id="message"></div>
</div>
<div style="padding-bottom:10px;">
<!-- 发送给他<input type="text" id ="sendTo" /><br/> -->
发送内容<input type="text" id ="sendText" /><br/>
<button id ="btnSend" οnclick="sendMsg();">点击发送</button>
</div>
</body>
<script src="./js/jquery.js"></script>
<!-- stomp协议的客户端脚本 -->
<script src="./js/stomp.js"></script>
<!-- SockJS的客户端脚本 -->
<script src="./js/sockjs.js"></script>
<script type="text/javascript">

    /**
     /queue/queuename:使用默认转发器订阅/发布消息,默认由stomp自动创建一个持久化队列

     /amq/queue/queuename:与/queue/queuename的区别在于队列不由stomp自动进行创建,队列不存在失败

     /topic/routing_key:通过amq.topic转发器订阅/发布消息,订阅时默认创建一个临时队列,通过routing_key与topic进行绑定

     /temp-queue/xxx:创建一个临时队列(只能在headers中的属性reply-to中使用),可用于发送消息后通过临时队列接收回复消息,接收通过client.onreceive

     /exchange/exchangename/[routing_key]:通过转发器订阅/发布消息,转发器需要手动创建

     client.subscribe(destination,callback,headers) :订阅消息

     client.send(destination,headers,body):发布消息

     client.unsubscribe(id):取消订阅,id为订阅时返回的编号

     client.onreceive:默认接收回调从临时队列获取消息

     */
     var user="";
     var sender="";
     var receiver="";
     var spea="\u001f";
	$(function(){
		console.log(spea);
		 var name=prompt("Please enter your name","");
		  if (name!=null && name!="")
		    {
			  user=name.split(",")[0];
			  sender=name.split(",")[0];
			  receiver=name.split(",")[1];
		    }
		 window.setInterval(function (){
		client.send("aliveMsg",{"content-type":"text/plain"},user);
		 },3000);
	});
    var ws = new WebSocket('ws://172.16.23.149:15674/ws');
    // 获得Stomp client对象
    var client = Stomp.over(ws);

    // SockJS does not support heart-beat: disable heart-beats
    client.heartbeat.outgoing = 0;
    client.heartbeat.incoming = 0;

    // 定义连接成功回调函数
    var on_connect = function (x) {
        console.log("x:"+x);
        //data.body是接收到的数据
        client.subscribe(sender+spea+receiver+"myQueue", function (data) {
            var msg = data.body;
            $("#message").append('<span style="float:left;">'+receiver+':' + msg + '</span><br/>');
        });
        client.subscribe(user+"onAlive", function (data) {
            var msg = data.body;
            console.log(msg);
        });
    };
	
    // 定义错误时回调函数
    var on_error = function () {
        console.log('error');
    };

    // 连接RabbitMQ
    client.connect('sandi_zea', 'sandi8823', on_connect, on_error, '/');
    console.log(">>>连接上http://172.16.23.149:15674");

	function sendMsg(){
		var  msg=$("#sendText").val();
		//var to=$("#sendTo").val();
		 $("#message").append('<span style="float:right;">'+msg+':'+ sender  + '</span><br/>');
		client.send(receiver+spea+sender+"myQueue",{"content-type":"text/plain"},msg);
		}
	
	
</script>
</html>

js直接引入就行,不需要改动。