Upgrading a TCP Server to WebSocket in Go: Practical Step‑by‑Step Guide
This article walks through converting a Go‑based TCP private‑protocol server to support WebSocket on the same port, covering library selection, client and server implementation, request upgrading, and a complete usage example with code snippets.
Today’s article records a time‑critical task of upgrading a private TCP protocol server to support WebSocket on the same port using Go.
WebSocket library
Upgrading from TCP to WebSocket
Usage method
WebSocket Library
The official Go library golang.org/x/net/websocket can be cloned from https://github.com/golang/net.git into go/src/golang.org/x/net. Its API is straightforward; documentation is available at pkg.go.dev/websocket.
Client
conn, err := websocket.Dial(url, subprotocol, origin)
websocket.Message.Send(conn, "")
var b []byte
websocket.Message.Receive(conn, &b)The client creates a *websocket.Conn via websocket.Dial(). subprotocol specifies a sub‑protocol (optional), and origin is the request origin (e.g., http://host). Using websocket.Message simplifies sending and receiving whole frames compared to raw Read/Write on the connection. subprotocol indicates a specific protocol format (e.g., different serialization methods); it can be empty. origin denotes the requesting website, usually just http://<host>.
Server
var recv func([]byte)
var err error
f := func(conn *websocket.Conn) {
for {
var b []byte
err = websocket.Message.Receive(conn, &b)
if err != nil {
return
} else {
recv(b)
}
}
}
websocket.Handler(f).ServeHTTP(w, r)The server can upgrade an HTTP request using websocket.Handler or websocket.Server, which invoke a callback receiving a *websocket.Conn for business logic.
Both Handler and Server can be registered with net/http, or their ServeHTTP method can be called directly. Handler accepts a simple callback function, allowing the use of closures for richer context.
Connection Send/Receive
Using websocket.Message provides simple binary or string send/receive with each call representing a complete frame. The websocket.Codec interface supports custom serialization; websocket.JSON is a ready‑made JSON codec. Although *websocket.Conn implements net.Conn, using raw Read/Write bypasses WebSocket framing and is unnecessary.
Upgrading from TCP to WebSocket
Because the private TCP protocol and the WebSocket handshake have completely different headers, checking whether the first three bytes equal GET distinguishes a WebSocket upgrade request. The challenge is converting a []byte plus a *net.TCPConn into an http.ResponseWriter and *http.Request for the standard WebSocket handler.
http.ResponseWriter
type wsFakeWriter struct {
conn *net.TCPConn
rw *bufio.ReadWriter
}
func makeHttpResponseWriter(conn *net.TCPConn) *wsFakeWriter {
w := new(wsFakeWriter)
w.conn = conn
w.rw = bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
return w
}
func (w *wsFakeWriter) Header() http.Header { return nil }
func (w *wsFakeWriter) WriteHeader(int) { /* handle upgrade failure */ }
func (w *wsFakeWriter) Write(b []byte) (int, error) { return 0, nil }
func (w *wsFakeWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.conn, w.rw, nil }*http.Request
func joinBufferAndReader(buffer []byte, reader io.Reader) io.Reader {
return io.MultiReader(bytes.NewReader(buffer), reader)
}
func takeHttpRequest(buffer []byte, conn *net.TCPConn) (*http.Request, error) {
r := joinBufferAndReader(buffer, conn)
return http.ReadRequest(bufio.NewReader(r))
}Go’s standard library makes the conversion straightforward: a []byte can become an io.Reader, and *net.TCPConn already implements io.Reader. Combining them with io.MultiReader lets http.ReadRequest parse the request without extra parsing logic.
Usage Method
func WebsocketOnTCP(buffer []byte, conn *net.TCPConn, recv func(*Package)) error {
req, err := takeHttpRequest(buffer, conn)
if err != nil { return err }
f := func(ws *websocket.Conn) { err = doWebSocket(ws, recv) }
w := makeHttpResponseWriter(conn)
websocket.Handler(f).ServeHTTP(w, req)
return err
}
func doWebSocket(conn *websocket.Conn, recv func(*Package)) error {
remoteAddr := conn.RemoteAddr()
reply := func(b []byte) error { websocket.Message.Send(conn, b); return nil }
for {
var b []byte
err := websocket.Message.Receive(conn, &b)
if err != nil { return err }
pack := new(Package)
pack.Addr = remoteAddr
pack.Content = b
pack.Reply = reply
recv(pack)
}
}The above provides a rough but functional example: it upgrades a raw TCP connection to a WebSocket, handles message exchange, and forwards received data to a user‑provided callback. Thread‑safety and upgrade‑failure handling are not fully verified.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
