Browse Source

readme, example improvements

master
mort 8 years ago
parent
commit
98093401c0
3 changed files with 90 additions and 6 deletions
  1. 82
    0
      README.md
  2. 4
    3
      examples/server.js
  3. 4
    3
      index.js

+ 82
- 0
README.md View File

@@ -0,0 +1,82 @@
# SockSugar

SocSugar is a rather simple library to simplify working with WebSockets. It makes WebSockets work somewhat like regular HTTP requests.

## Usage

### Requests

Requests resemble HTTP requests, where the client send data to the server and wait for a response.

On the server side:

var SockSugar = require("socksugar");

var server = new SockSugar({
port: 8081
});

server.on("connection", function(socket) {
console.log("Connection!");

socket.on("request", function(req) {
console.log("Request for "+req.url);
console.log(req.data);

req.respond({
msg: "No."
});
});
});

On the client side:

var sock = new SockSugar("ws://example.com");

sock.on("ready", function() {
sock.send("hi", {
msg: "Hi!"
}, function(err, data) {
console.log(data);
}
});

The server side console will say:

Connection!
Request for hi
{ msg: 'Hi!' }

The client side console will say:

{ msg: 'No.' }

### Events

Unlike HTTP, the server can push data to the client. Here's a simple example, where writing something in the console will emitt an event to all connected clients and displayed with alert().

On the server side:

var SockSugar = require("socksugar");

var server = new SockSugar({
port: 8081
});

process.stdin.on("data", function(data) {
var str = data.toString("utf8");

server.socks.forEach(function(sock) {
sock.send("myEvent", {
msg: str
});
});
});

On the client side:

var sock = new SockSugar("ws://example.com");

sock.on("myEvent", function(data) {
alert(data.msg);
});

+ 4
- 3
examples/server.js View File

@@ -7,11 +7,12 @@ var server = new SockSugar({
server.on("connection", function(sock) {
console.log("connection!");

sock.on("myMsg", function(req) {
sock.on("request", function(req) {
console.log("Request for "+req.url);
console.log(req.data);

req.reply({
foo: "bar"
msg:" Hello there!"
});
});
});
@@ -24,7 +25,7 @@ process.stdin.on("data", function(data) {

server.socks.forEach(function(sock) {
sock.send("myEvent", {
msg: str.replace(/^\w+\s+/, "")
msg: str.replace(/^\w+\s+/, "").trim()
});
});
} else {

+ 4
- 3
index.js View File

@@ -3,8 +3,9 @@ var events = require("events");
var util = require("util");

//Request {
function Request(sock, data, requestId) {
function Request(sock, url, data, requestId) {
this.data = data;
this.url = url;

this._sock = sock;
this._requestId = requestId;
@@ -48,9 +49,9 @@ var util = require("util");
this.emit("error", err);
}

var req = new Request(this, obj.d, obj.r);
var req = new Request(this, obj.n, obj.d, obj.r);

this.emit(obj.n, req);
this.emit("request", req);
}.bind(this));
}
util.inherits(Socket, events.EventEmitter);

Loading…
Cancel
Save