Feat: done tcp

This commit is contained in:
2025-11-10 10:02:55 +08:00
parent 78d89595a1
commit 9a39bcda40
17 changed files with 689 additions and 0 deletions

51
tcp/socket.go Normal file
View File

@@ -0,0 +1,51 @@
package tcp
import (
"encoding/json"
"net"
)
type ShutdownFunc func() error
type SocketConn struct {
conn net.Conn
Shutdown ShutdownFunc
}
func (self *SocketConn) Read() ([]byte, error) {
return readFrame(self.conn)
}
func (self *SocketConn) Write(b []byte) error {
return sendFrame(self.conn, b)
}
func Dial(addr, route string) (*SocketConn, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
header := RequestHeader{
Method: MethodSOCKET,
Route: route,
}
rawHeader, err := json.Marshal(header)
if err != nil {
return nil, err
}
if err := sendFrame(conn, rawHeader); err != nil {
return nil, err
}
// Empty body
if err := sendFrame(conn, []byte{}); err != nil {
return nil, err
}
return &SocketConn{
conn: conn,
Shutdown: func() error {
return conn.Close()
},
}, nil
}