未加星标

Sending websocket messages Part 2

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

In theprevious post, we established a websocket connection to our server. In this blog post, we learn how to send websocket messages to single and multiple users.

Theoretical Introduction

WebSocket has one of the simplest API. There are only 2 methods and 4 events. In this post, we will examine the send method. Xocket.io has certain peculiarities that you have to be aware of when sending messages. It relates to the format of the websocket message and the definition of the recipients.

Message format

The simplest websocket message looks like this


Sending websocket messages   Part 2

It’s a simple javascript object with three properties. It’s very important that the from property is exactly in the @UserName() format (Check the websocket.nsf > Users by URI view for the correct format, if you get stuck!). This simple format is good if you want a simple chat application. However, most of the time, we usemore complicated messages.

The recipient broadcast

You have multiple options how to address your websocket messages. The simplest is the

"to": "broadcast"

format. It’s very powerful, it sends your message to every user on your server REGARDLESS of which application they are logged in. This type of messaging can be useful notifying your users for server related issues (i.e. “Server is going down for maintenance…”).

Specific user

You can send messages to specific users by using their canonical user names:

"to": "CN=Csaba Kiss/O=csaba" //sends a message to a specific user logged into any application on the server URI based recipients "to": "/wsApp.nsf/*" //send a message to everybody logged into the wsApp.nsf application "to":"/wsApp.nsf/index.xsp*" //sends a message to everybody who is on the index page in the wsApp application "to":/wsApp.nsf/index.xsp/CN=CsabaKiss/O=csaba" //send a message to a specific user on a specific page of the wsApp application

This is very neat, I use URI targetingmost of the time. Be careful with word capitalization. It’s JavaScript, and if you have a different case application in your websocket.nsf Users By Uri view, the messages will not be delivered.

Role based recipients "to": "/wsApp.nsf/*[mgr],[admin]" //sends a message to users with mgr or admin roles on any page of the wsApp

You can see that message targeting can be very specific and you can tune it very precisely according to your needs.

Multiple recipients

You can also list multiple users as your recipients, however, you need to change the to property to targets :

"targets": ["CN=Csaba Kiss/O=csaba", "CN=Other User/O=csaba", "/app.nsf*"]

Themultiple recipients are in an array of strings. I use this option, when I target my server and the users on the server with my message.

These are all the various recipients you can use with the xocket.io plugin.

Complex message Most of the time, you will send more complex messages than just a simple chat message. Here is an example of a more complex websocket message:
Sending websocket messages   Part 2

You can see that this message contains another property, called data , which is itself a JavaScript object. This is where you put most of your websocket logic in your application. For example, the message above contains a msg.data.application property. This allows you to filter messages coming form various applications. You can set this property to “wsApp” in all the messages that comes from the wsApp application.

The message above is a status message that logs if a user goes idle after for while. For example you can have an idle function that sends out this message if the user has not interacted with the application for 5 minutes. When other users receive this message, the wsApp application will automatically put the idle user in a category, so other users know the he/she is away.

You could send binary data (i.e. files) also in the data object, if they are properly encoded.

Continue Building the wsApp

In the first part of this blog series, we began to build our first websocket enabled application and established a websocket connection. If you want to continue where we left last time, check out the part-1 branch from the github repo.

Our application will do a very simple thing. It will have a shape and a button on the page. Whenever the user clicks the button the size, color, and border of the shape will change randomly. These changes will be communicated to other users using websocket messaging, so that the shapes are synchronized among the users in all browser windows.


Sending websocket messages   Part 2

I hope this application will demonstrate clearly how to send websocket messages. how to handle received websocket messages and also how to interact with your Domino database back-end using websocket. So let’s continue where we left off last time.

ccShape

Create a new ccShape custom control and paste this code in the source code.

<?xmlversion="1.0" encoding="UTF-8"?> <xp:viewxmlns:xp="http://www.ibm.com/xsp/core"> <xp:this.resources> <xp:styleSheethref="/shape.css"></xp:styleSheet> </xp:this.resources> <xp:divstyleClass="text-center col-sm-8 col-sm-offset-2" style="border: 1px solid #DDD; padding: 5px;"> <xp:divid="shapeDiv" style="min-height:100px" styleClass="shape"></xp:div> <xp:buttonstyleClass="btn btn-primary" id="luckyBtn" value="Click me!"> </xp:button> </xp:div> </xp:view>

Create a a new style sheet and call it shape.css

.shape { transition: all 2s ease-in-out; margin:auto; margin-bottom: 20px; border: dottedred 2px; }

This simple custom controls contains two simple divs and a button. The inner div (line 7)has a style class associated with it that is initiated from the shape.css. The outer div (line 6) is only a container with bootstrap classes and a thin gray border. At the moment, the button does not do anything. Let’s fix that. Add this code to the onclick event of the button:

function getRandomNumber (min, max) { return Math.floor(Math.random() * (max-min)) + min; } var borders = ["solid", "dotted", "dashed", "double", "groove", "ridge", "inset", "outset", "none"]; var border = getRandomNumber(1,10) + "px firebrick " + borders[getRandomNumber(0,8)]; var backgroundColor = "rgba(" + getRandomNumber(0,255)+ ","+ getRandomNumber(0,255) + "," + getRandomNumber(0,255)+ "," + getRandomNumber(0,10)/10+")"; var borderRadius = getRandomNumber(0, 60)+ "% "+ getRandomNumber(0, 60)+ "%"; var divHeight = getRandomNumber(10,300)+"px"; var divWidth = getRandomNumber(10,700)+"px"; var shape = {}; shape.border = border; shape.bgColor = backgroundColor; shape.borderRadius = borderRadius; shape.divHeight = divHeight; shape.divWidth = divWidth; var shapeMessage = createShapeMessage(shape); ws.send(shapeMessage);

Let’s just see what we are doing here.

Line 1-3contains a simple number randomizer function that returns a random integer between the min and max number.

Line 5contains an array of border css property strings that most modern browsers understand.

Line 6-10contains code that randomizes the shape properties: border, backgroundColor, border radius width and height.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaScriptJavaWebSocketUT
分页:12
转载请注明
本文标题:Sending websocket messages Part 2
本站链接:http://www.codesec.net/view/484069.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(32)