"WebSocket"---implement one-to-one chat function

Source: Internet
Author: User

Implement one-to-one chat features

function Description : Implement a and B separate chat function, that is, a message to B can only b receive, the same B to a message can only a receive.

This blog is built on the basis of the previous blog address: "WebSocket"---realize the game announcement function. The source code will be written in all other cases, uploading to GitHub, the time will be the source address.

First look at the demo effect:

First, case analysis1, Ptpcontoller
/***/@Controllerpublicclass  ptpcontoller {    @Autowired     Private websocketservice ws;    @MessageMapping ("/ptp/single/chat")    publicvoid  singlechat ( Inmessage message) {        ws.sendchatmessage (message);}    }

Here and the previous announcement message, the biggest difference is that the interface does not pass @sendto ("/topic/game_chat") to send messages.

(1) difference between @SendTo and simpmessagingtemplate

Spring WebSocket annotation-based @sendto and @sendtouser are convenient, but have limitations, such as my needs, I want to manually push the message to someone, or a specific group of people, how to do,

@SendTo can only be pushed to everyone (it is a specific address, not a bit flexible), @SendToUser can only be pushed to the person requesting the message, then we can use simpmessagingtemplate this class

Simpmessagingtemplate, there are two ways to push.

Convertandsend (destination, payload);            //  convertandsendtouser (user, destination, payload); // pushes a message to a fixed user subscription path, similar to @sendtouser

2, Websocketservice
ImportCom.jincou.websocket.model.InMessage;ImportCom.jincou.websocket.model.OutMessage;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.messaging.simp.SimpMessagingTemplate;ImportOrg.springframework.stereotype.Service;/*** Function Description: Simple message template, used to push messages*/@Service Public classWebsocketservice {@AutowiredPrivatesimpmessagingtemplate template; /*** Simple Point-to-point chat room*/     Public voidsendchatmessage (Inmessage message) {//we can see that the most flexible template is that we can get the parameters from the front end to specify the subscription address//The preceding parameter is the subscription address, and the following parameter is the message informationTemplate.convertandsend ("/chat/single/" +Message.getto (),NewOutmessage (Message.getfrom () + "Send:" +message.getcontent ())); }

3, App.js

Other places and announcements of the App.js, only the following two points made a little change

function Connect () {var from= $ ("#from"). Val (); var socket=NewSockjs ('/endpoint-websocket '); Stompclient=stomp.over (socket); Stompclient.connect ({}, function (frame) {setconnected (true); Console.log (' Connected: ' +frame); //1,With +from, you can flexibly use a message from the current user to specify the user's subscription address. Stompclient.subscribe ('/chat/single/' +From , function (result) {showcontent (Json.parse (result.body));    }); });} function Sendname () {//2,This sends out the content information, but also sends the sender user information, and the recipient's informationStompclient.send ("/app/ptp/single/chat", {}, json.stringify ({' content ': $ ("#content"). Val (), ' to ': $ ("#to"). Val (), ' From ': $ ("#from") . Val ()});}

4, user.html

The rest of the place is the same as the previous announcement, here are the changes

<divclass= "Col-md-6" > <formclass= "Form-inline" > <divclass= "Form-group" > <input type= "Text"id= "from" class= "Form-control" placeholder= "I Am" > <input type= "Text"id= "to" class= "Form-control" placeholder= "Send to who" > <input type= "Text"id= "Content" class= "Form-control" placeholder= "Please enter ..." > </div> <butt Onid= "Send" class= "Btn Btn-default" type= "submit" > Send </button> </form> </div>

5, then the whole line of thought Wisp

Example of sending a message with a to B

(1) Form input box input: "A", to input box input "B" click "Connect" to establish WebSocket connection

(2) Then a user's subscription address is '/chat/single/a '

(3) Front end in the "Content" button enter "Did you eat chicken today?" ", then click the" Send "button

(4) The backstage by accepting processing has become:

Template.convertandsend ("/chat/single/b",new outmessage ("A send: Did you eat chicken today?") "));

Then B sends the exact same nature to A. You can implement one-on-one chats.

Note: This is just a demo, not really one-on chat, generally if the implementation of one-to-one chat, then the form and to should be unique, such as the user's userid, so that you can really achieve a one-to-one chat.

Think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Lieutenant Colonel "19"

"WebSocket"---implement one-to-one chat function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.