soheilhy/cmux 网络端口复用服务
同一个端口可以进行不同的操作还是很有用的,比如一个端口同时提供ssh,http,rpc 服务
soheilhy/cmux 是一个不错的选择,以下是一个简单的试用,代码来自官方文档
代码
main.go
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"net/rpc"
"strings"
"github.com/soheilhy/cmux"
"golang.org/x/net/websocket"
"google.golang.org/grpc"
grpchello "google.golang.org/grpc/examples/helloworld/helloworld"
)
type exampleHTTPHandler struct{}
func (h *exampleHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "example http response")
}
func serveHTTP(l net.Listener) {
s := &http.Server{
Handler: &exampleHTTPHandler{},
}
if err := s.Serve(l); err != cmux.ErrListenerClosed {
panic(err)
}
}
func EchoServer(ws *websocket.Conn) {
if _, err := io.Copy(ws, ws); err != nil {
panic(err)
}
}
func serveWS(l net.Listener) {
s := &http.Server{
Handler: websocket.Handler(EchoServer),
}
if err := s.Serve(l); err != cmux.ErrListenerClosed {
panic(err)
}
}
type ExampleRPCRcvr struct{}
func (r *ExampleRPCRcvr) Cube(i int, j *int) error {
*j = i * i
return nil
}
func serveRPC(l net.Listener) {
s := rpc.NewServer()
if err := s.Register(&ExampleRPCRcvr{}); err != nil {
panic(err)
}
for {
conn, err := l.Accept()
if err != nil {
if err != cmux.ErrListenerClosed {
panic(err)
}
return
}
go s.ServeConn(conn)
}
}
type grpcServer struct {
// must embedd this
grpchello.UnimplementedGreeterServer
}
func (s *grpcServer) SayHello(ctx context.Context, in *grpchello.HelloRequest) (
*grpchello.HelloReply, error) {
return &grpchello.HelloReply{Message: "Hello " + in.Name + " from cmux"}, nil
}
func serveGRPC(l net.Listener) {
grpcs := grpc.NewServer()
grpchello.RegisterGreeterServer(grpcs, &grpcServer{})
if err := grpcs.Serve(l); err != cmux.ErrListenerClosed {
panic(err)
}
}
type mylogin struct {
}
func (my mylogin) ServeHTTP(res http.ResponseWriter, req *http.Request) {
res.Header().Add("Content-Type", "text/html")
res.Write([]byte("dalong demo"))
}
func main() {
l, err := net.Listen("tcp", ":50051")
if err != nil {
log.Panic(err)
}
m := cmux.New(l)
// We first match the connection against HTTP2 fields. If matched, the
// connection will be sent through the "grpcl" listener.
grpcl := m.Match(cmux.HTTP2HeaderFieldPrefix("content-type", "application/grpc"))
//Otherwise, we match it againts a websocket upgrade request.
wsl := m.Match(cmux.HTTP1HeaderField("Upgrade", "websocket"))
// Otherwise, we match it againts HTTP1 methods. If matched,
// it is sent through the "httpl" listener.
httpl := m.Match(cmux.HTTP1Fast())
// If not matched by HTTP, we assume it is an RPC connection.
rpcl := m.Match(cmux.Any())
// Then we used the muxed listeners.
go serveGRPC(grpcl)
go serveWS(wsl)
// go serveHTTP(httpl)
go serveRPC(rpcl)
go func() {
http.Serve(httpl, &mylogin{})
}()
if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") {
panic(err)
}
}
简单说明:
以上代码使用了同一个端口提供http,websocket,rpc 服务(grpc,以及rpc)
运行效果
说明
类似的有一个比较好玩的linux 内核对于tcp reuseport 特性的支持,可以复用端口(比如软件升级)同时提升系统的性能,实际上我们可以
集成go_reuseport
核心代码部分只需要简单的修改
l, err := reuseport.Listen("tcp", ":50051")
if err != nil {
log.Panic(err)
}
参考资料
https://github.com/soheilhy/cmux
https://github.com/rongfengliang/cmux-learning
https://github.com/kavu/go_reuseport
https://segmentfault.com/a/1190000020524323
http://www.blogjava.net/yongboy/archive/2015/02/12/422893.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2019-12-16 pcp 基本使用
2018-12-16 ipfs docker 运行试用
2018-12-16 hermes 试用
2017-12-16 好用的 convert freestyle jenkins jobs to pipeline 插件使用
2017-12-16 MkDocs 搭建试用
2016-12-16 k8s dashboard 部署发布
2016-12-16 lvs的dr模式分析(二)