1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

_examples/websocket/basic: add a nodejs client and provide a README.md on how to run the websocket clients and the server

Former-commit-id: a98a80996d7d95fa947e72c71803407682229fa7
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-06-13 12:15:01 +03:00
parent 5f148987f7
commit 272566950d
14 changed files with 126 additions and 92 deletions

View File

@@ -0,0 +1,62 @@
# Basic Example
At the end of this example you will be able to run a websocket server
and clients for all platforms (Go, Browser and Nodejs).
![](overview.png)
Open as many clients as you want to try out and start typing.
This example contains only the basics, however, the library supports rooms, native websocket messages, any data can be sent and received (i.e protobufs, json) and all kinds of broadcasting and connections collections.
## How to run
### Server
Open a terminal window instance and execute:
```sh
$ go run server.go # start the websocket server.
```
### Client (Go)
Start a new terminal instance and execute:
```sh
$ cd ./go-client
$ go run client.go # start the websocket client.
# start typing...
```
### Client (Browser)
Navigate to <http://localhost:8080> and start typing.
The `./browser/index.html` should be served, it contains the client-side code.
### Client (Browserify)
Install [NPM](https://nodejs.org) first, then start a new terminal instance and execute:
```sh
$ cd ./browserify
$ npm install
# build the modern browser-side client:
# embed the neffos.js node-module and app.js
# into a single ./browserify/bundle.js file
# which ./browserify/client.html imports.
$ npm run-script build
```
Navigate to <http://localhost:8080/browserify/client.html> and start typing.
### Client (Nodejs)
Install [NPM](https://nodejs.org) if you haven't already and then, start a new terminal instance and execute:
```sh
$ cd nodejs-client
$ npm install
$ node client.js # start the websocket client.
# start typing.
```

View File

@@ -10,7 +10,7 @@
However, `neffos.(min.)js` is a NPM package too so alternatively,
you can use it as dependency on your package.json and all nodejs-npm tooling become available:
see the "browserify" example for more-->
<script src="https://cdn.jsdelivr.net/npm/neffos.js@0.1.8/dist/neffos.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/neffos.js@0.1.12/dist/neffos.min.js"></script>
<script>
// `neffos` global variable is available now.
var scheme = document.location.protocol == "https:" ? "wss" : "ws";
@@ -28,6 +28,8 @@
}
function handleNamespaceConnectedConn(nsConn) {
nsConn.emit("Hello from browser client side!");
let inputTxt = document.getElementById("input");
let sendBtn = document.getElementById("sendBtn");
@@ -62,7 +64,7 @@
// You can either wait to conenct or just conn.connect("connect")
// and put the `handleNamespaceConnectedConn` inside `_OnNamespaceConnected` callback instead.
// const nsConn = await conn.connect("default");
// handleNamespaceConnectedConn(nsConn);
// nsConn.emit(...); handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {

View File

@@ -1,11 +0,0 @@
# Browserify example
```sh
$ npm install --only=dev # install browserify from the devDependencies.
$ npm run-script build # browserify and minify the `app.js` into `bundle.js`.
$ cd ../ && go run server.go # start the neffos server.
```
> make sure that you have [golang](https://golang.org/dl) installed to run and edit the neffos (server-side).
That's all, now navigate to <http://localhost:8080/browserify>.

View File

@@ -6,6 +6,7 @@ var port = document.location.port ? ":" + document.location.port : "";
var wsURL = scheme + "://" + document.location.hostname + port + "/echo";
var outputTxt = document.getElementById("output");
function addMessage(msg) {
outputTxt.innerHTML += msg + "\n";
}
@@ -16,6 +17,8 @@ function handleError(reason) {
}
function handleNamespaceConnectedConn(nsConn) {
nsConn.emit("chat", "Hello from browser(ify) client-side!");
const inputTxt = document.getElementById("input");
const sendBtn = document.getElementById("sendBtn");
@@ -50,6 +53,7 @@ async function runExample() {
// and put the `handleNamespaceConnectedConn` inside `_OnNamespaceConnected` callback instead.
// const nsConn = await conn.connect("default");
// handleNamespaceConnectedConn(nsConn);
// nsConn.emit(...); handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {
@@ -57,5 +61,4 @@ async function runExample() {
}
}
runExample();
runExample();

File diff suppressed because one or more lines are too long

View File

@@ -24,20 +24,15 @@ const (
var clientEvents = websocket.Namespaces{
namespace: websocket.Events{
websocket.OnNamespaceConnected: func(c *websocket.NSConn, msg websocket.Message) error {
log.Printf("[%s] connected to namespace [%s]", c, msg.Namespace)
log.Printf("connected to namespace: %s", msg.Namespace)
return nil
},
websocket.OnNamespaceDisconnect: func(c *websocket.NSConn, msg websocket.Message) error {
log.Printf("[%s] disconnected from namespace [%s]", c, msg.Namespace)
log.Printf("disconnected from namespace: %s", msg.Namespace)
return nil
},
"chat": func(c *websocket.NSConn, msg websocket.Message) error {
log.Printf("[%s] sent: %s", c.Conn.ID(), string(msg.Body))
// Write message back to the client message owner with:
// c.Emit("chat", msg)
// Write message to all except this client with:
c.Conn.Server().Broadcast(c, msg)
log.Printf("%s", string(msg.Body))
return nil
},
},
@@ -58,6 +53,8 @@ func main() {
panic(err)
}
c.Emit("chat", []byte("Hello from Go client side!"))
fmt.Fprint(os.Stdout, ">> ")
scanner := bufio.NewScanner(os.Stdin)
for {

View File

@@ -0,0 +1,35 @@
const neffos = require('neffos.js');
const stdin = process.openStdin();
const wsURL = "ws://localhost:8080/echo";
async function runExample() {
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
console.log("connected to namespace: " + msg.Namespace);
},
_OnNamespaceDisconnect: function (nsConn, msg) {
console.log("disconnected from namespace: " + msg.Namespace);
},
chat: function (nsConn, msg) { // "chat" event.
console.log(msg.Body);
}
}
});
const nsConn = await conn.connect("default");
nsConn.emit("chat", "Hello from Nodejs client side!");
stdin.addListener("data", function (data) {
const text = data.toString().trim();
nsConn.emit("chat", text);
});
} catch (err) {
console.error(err);
}
}
runExample();

View File

@@ -0,0 +1,8 @@
{
"name": "neffos.js.example.nodejsclient",
"version": "0.0.1",
"main": "client.js",
"dependencies": {
"neffos.js": "latest"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

View File

@@ -40,7 +40,7 @@ var serverEvents = websocket.Namespaces{
func main() {
app := iris.New()
websocketServer := websocket.New(
websocket.DefaultGorillaUpgrader, /*DefaultGobwasUpgrader can be used as well*/
websocket.DefaultGorillaUpgrader, /* DefaultGobwasUpgrader can be used too. */
serverEvents)
// serves the endpoint of ws://localhost:8080/echo
@@ -54,5 +54,5 @@ func main() {
// serves the npm browser websocket client usage example.
app.StaticWeb("/browserify", "./browserify")
app.Run(iris.Addr(":8080"))
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}