-
-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question\Websocket] How to send binary data with neffos(websocket)? #10
Comments
Please set SetBinary = true in neffos.Message neffos.Message Struct
|
@majidbigdeli Hi, thanks for your help. Here is my client var scheme = document.location.protocol == "https:" ? "wss" : "ws";
var port = document.location.port ? ":" + document.location.port : "";
var wsURL = scheme + "://" + document.location.hostname + port + "/stream";
function handleError(reason) {
console.log(reason);
}
function handleNamespaceConnectedConn(nsConn) {
}
// const username = window.prompt("Your username?");
async function runExample() {
// You can omit the "default" and simply define only Events, the namespace will be an empty string"",
// however if you decide to make any changes on this example make sure the changes are reflecting inside the ../server.go file as well.
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
handleNamespaceConnectedConn(nsConn)
},
_OnNamespaceDisconnect: function (nsConn, msg) {
},
stream: function (nsConn, msg) { // "stream" event.
console.log(msg.Body);
console.log(msg)
}
}
},{
headers: {
"X-Username": "",
}
});
// 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");
// nsConn.emit(...); handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {
handleError(err);
}
} |
Hello @StartAt24, can you provide us a reproducible code? |
Hello @kataras I think this issue Related To Neffos.js. in neffos.js function splitN
you use When We set |
@majidbigdeli Here is my current solution: |
@kataras sure. Here is my test code. Server: package main
import (
"github.com/kataras/iris"
"fmt"
"github.com/kataras/iris/websocket"
"github.com/kataras/neffos"
"time"
)
// 全局变量
var page = struct {
Title string
}{"Collector"}
func main(){
app := iris.New()
ws_server := startWebSocketServer(app)
go pub_thread(ws_server)
app.RegisterView(iris.HTML("./static", ".html"))
app.Get("/" ,func(ctx iris.Context){
ctx.ViewData("Page", page)
ctx.View("index.html")
})
app.HandleDir("/", "./static")
app.Run(iris.Addr(":5000"), iris.WithoutPathCorrection)
}
var serverEvents = websocket.Namespaces{
"default": websocket.Events{
websocket.OnNamespaceConnected: func(nsConn *websocket.NSConn, msg websocket.Message) error {
// with `websocket.GetContext` you can retrieve the Iris' `Context`.
ctx := websocket.GetContext(nsConn.Conn)
fmt.Printf("[%s] connected to namespace [%s] with IP [%s]\n",
nsConn, msg.Namespace,
ctx.RemoteAddr())
return nil
},
websocket.OnNamespaceDisconnect: func(nsConn *websocket.NSConn, msg websocket.Message) error {
fmt.Printf("[%s] disconnected from namespace [%s]\n", nsConn, msg.Namespace)
return nil
},
"stream": func(nsConn *websocket.NSConn, msg websocket.Message) error {
// room.String() returns -> NSConn.String() returns -> Conn.String() returns -> Conn.ID()
fmt.Printf("[%s] sent: %s", nsConn, string(msg.Body))
// Write message back to the client message owner with:
// nsConn.Emit("chat", msg)
// Write message to all except this client with:
nsConn.Conn.Server().Broadcast(nsConn, msg)
return nil
},
},
}
func startWebSocketServer(app *iris.Application) *neffos.Server{
server := websocket.New(websocket.DefaultGorillaUpgrader, serverEvents)
server.OnConnect = func(c *websocket.Conn) error {
fmt.Printf("[%s] connected to the server.\n", c)
return nil
}
server.OnDisconnect = func(c *websocket.Conn){
fmt.Printf("[%s] disconnected from the server.", c)
}
fmt.Printf("Listening on: %d\nPress CTRL/CMD+C to interrupt.\n", 5000)
idGen := func(ctx iris.Context) string {
if username := ctx.GetHeader("X-Username"); username != "" {
return username
}
return websocket.DefaultIDGenerator(ctx)
}
app.Get("/stream", websocket.Handler(server, idGen))
return server
}
func pub_thread(serve *neffos.Server){
// for png:= range in{
// serve.Broadcast(nil, neffos.Message{SetBinary: true, Body:png, Namespace: "default"})
// }
png:= [...] byte{'h','o','l','l','e'}
slice := png[:]
for{
serve.Broadcast(nil, neffos.Message{SetBinary: true, Body:slice, Namespace: "default"})
time.Sleep(1*time.Second)
}
} web: <html>
<button> useless button</button>
<script src="https://cdn.jsdelivr.net/npm/neffos.js@latest/dist/neffos.js"></script>
<script>
var scheme = document.location.protocol == "https:" ? "wss" : "ws";
var port = document.location.port ? ":" + document.location.port : "";
var wsURL = scheme + "://" + document.location.hostname + port + "/stream";
function handleError(reason) {
console.log(reason);
}
function handleNamespaceConnectedConn(nsConn) {
}
// const username = window.prompt("Your username?");
async function runExample() {
// You can omit the "default" and simply define only Events, the namespace will be an empty string"",
// however if you decide to make any changes on this example make sure the changes are reflecting inside the ../server.go file as well.
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
handleNamespaceConnectedConn(nsConn)
},
_OnNamespaceDisconnect: function (nsConn, msg) {
},
stream: function (nsConn, msg) { // "stream" event.
console.log(msg.Body);
console.log(msg)
}
}
},{
headers: {
"X-Username": "",
}
});
// 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");
// nsConn.emit(...); handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {
handleError(err);
}
}
runExample()
</script>
</html> Then you will got is from console
|
Hello @StartAt24 @majidbigdeli, try to use the latest neffos.js e.g. <script src="//cdn.jsdelivr.net/npm/neffos.js@latest/dist/neffos.min.js"></script> Results based on your example (just added the It's done by parsing the neffos part as utf-8 and let the body as array buffer (uint8) for maximum performance. |
@kataras ThankYou . |
@kataras @majidbigdeli thanks for your work! var serverEvents = websocket.Namespaces{
"default": websocket.Events{
websocket.OnNamespaceConnected: func(nsConn *websocket.NSConn, msg websocket.Message) error {
// with `websocket.GetContext` you can retrieve the Iris' `Context`.
ctx := websocket.GetContext(nsConn.Conn)
fmt.Printf("[%s] connected to namespace [%s] with IP [%s]\n",
nsConn, msg.Namespace,
ctx.RemoteAddr())
return nil
},
websocket.OnNamespaceDisconnect: func(nsConn *websocket.NSConn, msg websocket.Message) error {
fmt.Printf("[%s] disconnected from namespace [%s]\n", nsConn, msg.Namespace)
return nil
},
"stream": func(nsConn *websocket.NSConn, msg websocket.Message) error {
// room.String() returns -> NSConn.String() returns -> Conn.String() returns -> Conn.ID()
fmt.Printf("[%s] sent: %s", nsConn, string(msg.Body))
// Write message back to the client message owner with:
// nsConn.Emit("chat", msg)
// Write message to all except this client with:
// nsConn.Conn.Server().Broadcast(nsConn, msg)
return nil
},
},
}
func startWebSocketServer(app *iris.Application) *neffos.Server{
server := websocket.New(websocket.DefaultGorillaUpgrader, serverEvents)
server.SyncBroadcaster = true
server.OnConnect = func(c *websocket.Conn) error {
fmt.Printf("[%s] connected to the server.\n", c)
return nil
}
server.OnDisconnect = func(c *websocket.Conn){
fmt.Printf("[%s] disconnected from the server.", c)
}
fmt.Printf("Listening on: %d\nPress CTRL/CMD+C to interrupt.", 5000)
idGen := func(ctx iris.Context) string {
if username := ctx.GetHeader("X-Username"); username != "" {
return username
}
return websocket.DefaultIDGenerator(ctx)
}
app.Get("/stream", websocket.Handler(server, idGen))
return server
} Also i have write a test program. But in that program, everything works fine. So i have compared them. There is no diff. |
I have debug that. messages have all been send to the client. So the bug must be in |
@kataras @majidbigdeli Sorry to bother you. But i have found the bug. I'm using var isArrayBuffer = data instanceof ArrayBuffer;
var dts;
console.log(isArrayBuffer)
if (isArrayBuffer) {
var arr = new Uint8Array(data);
var sepCount = 1;
var lastSepIndex = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == messageSeparatorCharCode) { // sep char.
sepCount++;
lastSepIndex = i;
}
}
// Drop here!!!!!!!!!!!!
if (sepCount != validMessageSepCount) {
msg.isInvalid = true;
console.log("return at validMessageSepCount")
return msg;
}
dts = splitN(textDecoder.decode(arr.slice(0, lastSepIndex)), messageSeparator, validMessageSepCount - 2);
dts.push(data.slice(lastSepIndex + 1, data.length));
msg.SetBinary = true;
}
else {
dts = splitN(data, messageSeparator, validMessageSepCount - 1);
} I thank it is a bug. Cannot just split message by |
@kataras @majidbigdeli here is the reproducible code. package main
import (
"github.com/kataras/iris"
"fmt"
"github.com/kataras/iris/websocket"
"github.com/kataras/neffos"
"time"
)
// 全局变量
var page = struct {
Title string
}{"Collector"}
func main(){
app := iris.New()
ws_server := startWebSocketServer(app)
go pub_thread(ws_server)
app.RegisterView(iris.HTML("./static", ".html"))
app.Get("/" ,func(ctx iris.Context){
ctx.ViewData("Page", page)
ctx.View("index.html")
})
app.HandleDir("/", "./static")
app.Run(iris.Addr(":5000"), iris.WithoutPathCorrection)
}
var serverEvents = websocket.Namespaces{
"default": websocket.Events{
websocket.OnNamespaceConnected: func(nsConn *websocket.NSConn, msg websocket.Message) error {
// with `websocket.GetContext` you can retrieve the Iris' `Context`.
ctx := websocket.GetContext(nsConn.Conn)
fmt.Printf("[%s] connected to namespace [%s] with IP [%s]\n",
nsConn, msg.Namespace,
ctx.RemoteAddr())
return nil
},
websocket.OnNamespaceDisconnect: func(nsConn *websocket.NSConn, msg websocket.Message) error {
fmt.Printf("[%s] disconnected from namespace [%s]\n", nsConn, msg.Namespace)
return nil
},
"stream": func(nsConn *websocket.NSConn, msg websocket.Message) error {
// room.String() returns -> NSConn.String() returns -> Conn.String() returns -> Conn.ID()
fmt.Printf("[%s] sent: %s", nsConn, string(msg.Body))
// Write message back to the client message owner with:
// nsConn.Emit("chat", msg)
// Write message to all except this client with:
nsConn.Conn.Server().Broadcast(nsConn, msg)
return nil
},
},
}
func startWebSocketServer(app *iris.Application) *neffos.Server{
server := websocket.New(websocket.DefaultGorillaUpgrader, serverEvents)
server.OnConnect = func(c *websocket.Conn) error {
fmt.Printf("[%s] connected to the server.\n", c)
return nil
}
server.OnDisconnect = func(c *websocket.Conn){
fmt.Printf("[%s] disconnected from the server.", c)
}
fmt.Printf("Listening on: %d\nPress CTRL/CMD+C to interrupt.\n", 5000)
idGen := func(ctx iris.Context) string {
if username := ctx.GetHeader("X-Username"); username != "" {
return username
}
return websocket.DefaultIDGenerator(ctx)
}
app.Get("/stream", websocket.Handler(server, idGen))
return server
}
func pub_thread(serve *neffos.Server){
png:= [...] byte{';',';',';',';',';'}
slice := png[:]
for{
serve.Broadcast(nil, neffos.Message{SetBinary: true, Body:slice, Namespace: "default"})
time.Sleep(1*time.Second)
}
} Client <html>
<button> useless button</button>
<script src="https://cdn.jsdelivr.net/npm/neffos.js@latest/dist/neffos.js"></script>
<script>
var scheme = document.location.protocol == "https:" ? "wss" : "ws";
var port = document.location.port ? ":" + document.location.port : "";
var wsURL = scheme + "://" + document.location.hostname + port + "/stream";
function handleError(reason) {
console.log(reason);
}
function handleNamespaceConnectedConn(nsConn) {
}
// const username = window.prompt("Your username?");
async function runExample() {
// You can omit the "default" and simply define only Events, the namespace will be an empty string"",
// however if you decide to make any changes on this example make sure the changes are reflecting inside the ../server.go file as well.
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
handleNamespaceConnectedConn(nsConn)
},
_OnNamespaceDisconnect: function (nsConn, msg) {
},
stream: function (nsConn, msg) { // "stream" event.
console.log(msg.Body);
console.log(msg)
}
}
},{
headers: {
"X-Username": "",
}
});
// 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");
// nsConn.emit(...); handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {
handleError(err);
}
}
runExample()
</script>
</html> |
For everybody else, continue at: #20 |
#387 I have read this issue. But cannot found,
websocket.Config
Then i found that,
Iris websocket library is now merged with the neffos real-time framework
But i cann't find a correct way to send
binary data
withneffos
.Is there any config for neffos to send
binary
instead ofstring
?The text was updated successfully, but these errors were encountered: