GithubHelp home page GithubHelp logo

Comments (2)

om26er avatar om26er commented on June 26, 2024 1

Thanks, I'll close the issue now

from nbio.

lesismal avatar lesismal commented on June 26, 2024

For client side, I think you can use nbhttp/websocket.Client directely.
net/http doesn't include websocket, if we use http.Client to send "upgrade" request and handshake ourselves, then convert it to nbio.Conn, it will be very complex, users need to do more, and we need to make some change for nbhttp.Engine to support the convertion.
Else if we use other websocket dialer, just can save the handshake processes, but still need to convert conn to nbio.Conn and make change for nbhttp.Engine.

If using nbio/nbhttp/websocket.Client directely, here is the full example including both server and client side handled by the same Engine:

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"time"

	"github.com/lesismal/llib/std/crypto/tls"
	"github.com/lesismal/nbio/nbhttp"
	"github.com/lesismal/nbio/nbhttp/websocket"
)

var (
	addr   = "localhost:8888"
	engine *nbhttp.Engine
)

func newServerUpgrader() *websocket.Upgrader {
	u := websocket.NewUpgrader()
	u.OnMessage(func(c *websocket.Conn, mt websocket.MessageType, data []byte) {
		fmt.Println("server OnMessage:", c.RemoteAddr().String(), mt, string(data))
		c.WriteMessage(mt, data)
	})
	u.OnClose(func(c *websocket.Conn, err error) {
		fmt.Println("server OnClose:", c.RemoteAddr().String(), err)
	})
	return u
}

func onWebsocket(w http.ResponseWriter, r *http.Request) {
	upgrader := newServerUpgrader()
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		panic(err)
	}
	wsConn := conn.(*websocket.Conn)
	fmt.Println("server OnOpen:", wsConn.RemoteAddr().String())
}

func newClientUpgrader() *websocket.Upgrader {
	u := websocket.NewUpgrader()
	u.OnMessage(func(c *websocket.Conn, mt websocket.MessageType, data []byte) {
		fmt.Println("cleint OnMessage:", c.RemoteAddr().String(), mt, string(data))
		time.AfterFunc(time.Second, func() {
			c.WriteMessage(mt, data)
		})
	})
	u.OnClose(func(c *websocket.Conn, err error) {
		fmt.Println("cleint OnClose:", c.RemoteAddr().String(), err)
	})
	return u
}

func client(i int) {
	u := url.URL{Scheme: "ws", Host: addr, Path: "/ws"}
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
	}
	dialer := &websocket.Dialer{
		Engine:          engine,
		Upgrader:        newClientUpgrader(),
		DialTimeout:     time.Second * 3,
		TLSClientConfig: tlsConfig,
	}
	c, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatalf("dial failed: %v", err)
	}
	log.Printf("dial success: %v", c.LocalAddr().String())
	c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("hello %v", i)))
}

func main() {
	flag.Parse()
	mux := &http.ServeMux{}
	mux.HandleFunc("/ws", onWebsocket)

	engine = nbhttp.NewEngine(nbhttp.Config{
		Network: "tcp",
		Addrs:   []string{addr},
		Handler: mux,
		IOMod:   nbhttp.IOModBlocking,
	})

	err := engine.Start()
	if err != nil {
		fmt.Printf("nbio.Start failed: %v\n", err)
		return
	}

	go func() {
		time.Sleep(time.Second / 10)
		for i := 0; i < 3; i++ {
			go client(i)
		}
	}()

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	<-interrupt
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	engine.Shutdown(ctx)
}

output:

2023/03/21 12:55:50.077 [INF] NBIO[NB] start
2023/03/21 12:55:50.078 [INF] Serve  NonTLS On: [[email protected]:8888]
server OnOpen: 127.0.0.1:41632
server OnOpen: 127.0.0.1:41634
2023/03/21 12:55:50 dial success: 127.0.0.1:41632
server OnOpen: 127.0.0.1:41636
2023/03/21 12:55:50 dial success: 127.0.0.1:41634
server OnMessage: 127.0.0.1:41634 1 hello 0
server OnMessage: 127.0.0.1:41632 1 hello 1
2023/03/21 12:55:50 dial success: 127.0.0.1:41636
cleint OnMessage: 127.0.0.1:8888 1 hello 0
cleint OnMessage: 127.0.0.1:8888 1 hello 1
server OnMessage: 127.0.0.1:41636 1 hello 2
cleint OnMessage: 127.0.0.1:8888 1 hello 2
server OnMessage: 127.0.0.1:41632 1 hello 1
server OnMessage: 127.0.0.1:41634 1 hello 0
server OnMessage: 127.0.0.1:41636 1 hello 2
cleint OnMessage: 127.0.0.1:8888 1 hello 1
cleint OnMessage: 127.0.0.1:8888 1 hello 2
cleint OnMessage: 127.0.0.1:8888 1 hello 0
......

from nbio.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.