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

MVC improvements: add HandleWebsocket that now registers events automatically based on the struct's methods(!) and fix a bug when more than one value of the same type is registered to a static field of a controller

Former-commit-id: e369d1426ac1a6b58314930a18362670317da3c1
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-07-09 12:16:19 +03:00
parent 85666da682
commit 450f20902d
18 changed files with 383 additions and 183 deletions

View File

@@ -0,0 +1,106 @@
<html>
<head>
<title>Online visitors MVC example</title>
<style>
body {
margin: 0;
font-family: -apple-system, "San Francisco", "Helvetica Neue", "Noto", "Roboto", "Calibri Light", sans-serif;
color: #212121;
font-size: 1.0em;
line-height: 1.6;
}
.container {
max-width: 750px;
margin: auto;
padding: 15px;
}
#online_visitors {
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<span id="online_visitors">1 online visitor</span>
</div>
<!-- the message's input -->
<input id="input" type="text" />
<!-- when clicked then a websocket event will be sent to the server, at this example we registered the 'chat' -->
<button id="sendBtn" disabled>Send</button>
<!-- the messages will be shown here -->
<pre id="output"></pre>
<!-- import the iris client-side library for browser from a CDN or locally.
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@latest/dist/neffos.min.js"></script>
<script type="text/javascript">
const wsURL = "ws://localhost:8080/websocket"
var outputTxt = document.getElementById("output");
function addMessage(msg) {
outputTxt.innerHTML += msg + "\n";
}
async function runExample() {
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
if (nsConn.conn.wasReconnected()) {
addMessage("re-connected after " + nsConn.conn.reconnectTries.toString() + " trie(s)");
}
let inputTxt = document.getElementById("input");
let sendBtn = document.getElementById("sendBtn");
sendBtn.disabled = false;
sendBtn.onclick = function () {
const input = inputTxt.value;
inputTxt.value = "";
nsConn.emit("OnChat", input);
addMessage("Me: " + input);
};
addMessage("connected to namespace: " + msg.Namespace);
},
_OnNamespaceDisconnect: function (nsConn, msg) {
addMessage("disconnected from namespace: " + msg.Namespace);
},
OnChat: function (nsConn, msg) { // "OnChat" event.
console.log(msg);
addMessage(msg.Body);
},
OnVisit: function (nsConn, msg) {
const newCount = Number(msg.Body); // or parseInt.
console.log("visit websocket event with newCount of: ", newCount);
var text = "1 online visitor";
if (newCount > 1) {
text = newCount + " online visitors";
}
document.getElementById("online_visitors").innerHTML = text;
},
}
});
conn.connect("default");
} catch (err) {
console.log(err)
}
}
runExample();
</script>
</body>
</html>

View File

@@ -1,41 +1,45 @@
package main
import (
"fmt"
"sync/atomic"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"github.com/kataras/iris/websocket"
"github.com/kataras/neffos"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
// optionally enable debug messages to the neffos real-time framework
// and print them through the iris' logger.
neffos.EnableDebug(app.Logger())
// load templates.
app.RegisterView(iris.HTML("./views", ".html"))
// render the ./views/index.html.
app.Get("/", func(ctx iris.Context) {
ctx.View("index.html")
})
// render the ./browser/index.html.
app.HandleDir("/", "./browser")
mvc.Configure(app.Party("/websocket"), configureMVC)
// Or mvc.New(app.Party(...)).Configure(configureMVC)
websocketAPI := app.Party("/websocket")
m := mvc.New(websocketAPI)
m.Register(
&prefixedLogger{prefix: "DEV"},
)
m.HandleWebsocket(&websocketController{Namespace: "default", Age: 42, Otherstring: "other string"})
websocketServer := neffos.New(websocket.DefaultGorillaUpgrader, m)
websocketAPI.Get("/", websocket.Handler(websocketServer))
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
func configureMVC(m *mvc.Application) {
ws := websocket.New(websocket.Config{})
// http://localhost:8080/websocket/iris-ws.js
m.Router.Any("/iris-ws.js", websocket.ClientHandler())
// This will bind the result of ws.Upgrade which is a websocket.Connection
// to the controller(s) served by the `m.Handle`.
m.Register(ws.Upgrade)
m.Handle(new(websocketController))
}
var visits uint64
func increment() uint64 {
@@ -47,36 +51,74 @@ func decrement() uint64 {
}
type websocketController struct {
// Note that you could use an anonymous field as well, it doesn't matter, binder will find it.
//
// This is the current websocket connection, each client has its own instance of the *websocketController.
Conn websocket.Connection
*neffos.NSConn `stateless:"true"`
Namespace string
Age int
Otherstring string
Logger LoggerService
}
func (c *websocketController) onLeave(roomName string) {
// or
// func (c *websocketController) Namespace() string {
// return "default"
// }
func (c *websocketController) OnNamespaceDisconnect(msg neffos.Message) error {
c.Logger.Log("Disconnected")
// visits--
newCount := decrement()
// This will call the "visit" event on all clients, except the current one,
// This will call the "OnVisit" event on all clients, except the current one,
// (it can't because it's left but for any case use this type of design)
c.Conn.To(websocket.Broadcast).Emit("visit", newCount)
c.Conn.Server().Broadcast(nil, neffos.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) update() {
func (c *websocketController) OnNamespaceConnected(msg neffos.Message) error {
// println("Broadcast prefix is: " + c.BroadcastPrefix)
c.Logger.Log("Connected")
// visits++
newCount := increment()
// This will call the "visit" event on all clients, including the current
// This will call the "OnVisit" event on all clients, including the current
// with the 'newCount' variable.
//
// There are many ways that u can do it and faster, for example u can just send a new visitor
// and client can increment itself, but here we are just "showcasing" the websocket controller.
c.Conn.To(websocket.All).Emit("visit", newCount)
c.Conn.Server().Broadcast(c, neffos.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) Get( /* websocket.Connection could be lived here as well, it doesn't matter */ ) {
c.Conn.OnLeave(c.onLeave)
c.Conn.On("visit", c.update)
func (c *websocketController) OnChat(msg neffos.Message) error {
ctx := websocket.GetContext(c.Conn)
// call it after all event callbacks registration.
c.Conn.Wait()
ctx.Application().Logger().Infof("[IP: %s] [ID: %s] broadcast to other clients the message [%s]",
ctx.RemoteAddr(), c, string(msg.Body))
c.Conn.Server().Broadcast(c, msg)
return nil
}
type LoggerService interface {
Log(string)
}
type prefixedLogger struct {
prefix string
}
func (s *prefixedLogger) Log(msg string) {
fmt.Printf("%s: %s\n", s.prefix, msg)
}

View File

@@ -1,63 +0,0 @@
<html>
<head>
<title>Online visitors MVC example</title>
<style>
body {
margin: 0;
font-family: -apple-system, "San Francisco", "Helvetica Neue", "Noto", "Roboto", "Calibri Light", sans-serif;
color: #212121;
font-size: 1.0em;
line-height: 1.6;
}
.container {
max-width: 750px;
margin: auto;
padding: 15px;
}
#online_visitors {
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<span id="online_visitors">1 online visitor</span>
</div>
<script src="/websocket/iris-ws.js"></script>
<script type="text/javascript">
(function () {
var socket = new Ws("ws://localhost:8080/websocket");
socket.OnConnect(function(){
// update the rest of connected clients, including "myself" when "my" connection is 100% ready.
socket.Emit("visit");
});
socket.On("visit", function (newCount) {
console.log("visit websocket event with newCount of: ", newCount);
var text = "1 online visitor";
if (newCount > 1) {
text = newCount + " online visitors";
}
document.getElementById("online_visitors").innerHTML = text;
});
socket.OnDisconnect(function () {
document.getElementById("online_visitors").innerHTML = "you've been disconnected";
});
})();
</script>
</body>
</html>