项目作者: ramlmn

项目描述 :
[Experimental] Custom node websocket server with rooms
高级语言: JavaScript
项目地址: git://github.com/ramlmn/node-ws.git
创建时间: 2016-11-05T17:38:28Z
项目社区:https://github.com/ramlmn/node-ws

开源协议:MIT License

下载


node-ws

Beware: Experimental technology ahead!

What is this?

Simply, it is a WebSocket server created in node using express and ws
modules.

How different is this from a WebSocket server?

A WebSocket server sends a message that it receives to all of it’s connected
clients, a thing that we don’t want sometimes.

So, we add users into specific rooms and restrict the communication within a
room.

What is a room?

A room is a virtual place to which users get added(actually join) based on the
room’s limit. So, every message you send is only received by users in the same
room that you are in.

How do I use this?

  • Clone the project
  • Go to the folder and run npm install to install the dependencies
  • Run npm start to start the WebSocket server
  • Go to http://localhost:8000 to check if it works

Note: node-ws uses only JSON to move message back and forth. If the
message is not in JSON, then it gets dumped.

Users in a room!

The number of users in a room can be controlled by changing ROOM_LIMIT(>=2)
in index.js.

Usage in the browser!

When a new connection is made to the WebSocket server, the first thing to do
after the connection is opened, is to send a join request followed by the name
of room you wish to join.

  1. let ws = new WebSocket('ws://localhost:8000');
  2. ws.onopen = () => {
  3. ws.send(JSON.stringify({
  4. type: 'join',
  5. room: 'my-private-room'
  6. }));
  7. };

The JSON object!

  1. {
  2. type: 'join | leave | msg | notif',
  3. room: 'my-private-room',
  4. body: 'A private message'
  5. }

When sending requests:

  • type: Type of request/response.

    Valid strings: 'join' | 'leave' | 'msg'

    'join' - A join request, used along with ‘room’
    'leave' - Request to leave the room(WebSocket connection is not closed)
    'msg' - Just send the messages to other users

  • room: Name of room to join

    Used along with type: 'join' only

When receiving responses:

  • type: Type of response message

    Valid responses: 'msg' | 'notif'

    'msg' - Specifying a message is received
    'notif' - Notification from server(like when users leave room)

  • body: Includes message content


Note: This is just some experimental technology that may not be of any
use for you. Use with caution!

License

Author: ramlmn

License: MIT