Comments (2)
Thanks, I'll close the issue now
from nbio.
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)
- just tested the performance of nbio tcp https on multicore system. it's great! but... how to do h2? HOT 1
- am i asking for a lot? pushing for tcp performance and nbios hit the mark but... HOT 18
- curious about the "total success" HOT 28
- how to increase the eventloop from the tls server example? HOT 5
- only 2,000 req/s with redis client example but using tls server example modification, i can get 25,000 req/s. what's wrong? HOT 2
- 请教大佬,在很短的时间里,向同一个conn推送多次数据 HOT 8
- 使用udp发送数据,会存在丢包! HOT 14
- Retract v1.5.4 HOT 6
- how to set so reuseport option for server? HOT 3
- 1.5.6 仍可能存在潜在bug HOT 35
- What is the principle of realizing 10 million connections to a single server? HOT 3
- WS客户端发送超高压缩率内容,可导致服务器OOM HOT 15
- onClose 没有调用 HOT 2
- InsecureSkipVerify=false的时候,无法进行TLS连接 HOT 7
- 请教下关于二进制数据压缩的问题 HOT 3
- LetsEncrypt HOT 3
- 大佬有交流群吗 HOT 4
- 关于nbio里,Conn结构体的小改动
- 关于nbio里,Conn结构体的小改动 HOT 2
- 双向的TLS验证通过后,在onWebsocket里,无法获取r.TLS HOT 9
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nbio.