ws: fixed bug in ws codes and now it worked

This commit is contained in:
nadoo committed 2018-07-22 18:21:27 +08:00
1 parent 9856f943ad
commit ff1fb8c291
6 files changed
+61 -56

No files matched your search

+21 -30
View File
@@ -13,6 +13,7 @@ import (
// Client ws client
type Client struct {
host string
path string
}
@@ -24,41 +25,29 @@ type Conn struct {
}
// NewClient .
func NewClient() (*Client, error) {
c := &Client{}
func NewClient(host, path string) (*Client, error) {
if path == "" {
path = "/"
}
c := &Client{host: host, path: path}
return c, nil
}
// NewConn .
func (c *Client) NewConn(rc net.Conn, target string) (*Conn, error) {
conn := &Conn{Conn: rc}
conn.Handshake()
return conn, nil
return conn, conn.Handshake(c.host, c.path)
}
// Handshake handshakes with the server using HTTP to request a protocol upgrade
//
// GET /chat HTTP/1.1
// Host: server.example.com
// Upgrade: websocket
// Connection: Upgrade
// Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
// Origin: http://example.com
// Sec-WebSocket-Protocol: chat, superchat
// Sec-WebSocket-Version: 13
//
// HTTP/1.1 101 Switching Protocols
// Upgrade: websocket
// Connection: Upgrade
// Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
// Sec-WebSocket-Protocol: chat
func (c *Conn) Handshake() error {
c.Conn.Write([]byte("GET / HTTP/1.1\r\n"))
c.Conn.Write([]byte("Host: echo.websocket.org\r\n"))
func (c *Conn) Handshake(host, path string) error {
c.Conn.Write([]byte("GET " + path + " HTTP/1.1\r\n"))
// c.Conn.Write([]byte("Host: 127.0.0.1\r\n"))
c.Conn.Write([]byte("Host: " + host + "\r\n"))
c.Conn.Write([]byte("Upgrade: websocket\r\n"))
c.Conn.Write([]byte("Connection: Upgrade\r\n"))
c.Conn.Write([]byte("Origin: http://127.0.0.1\r\n"))
c.Conn.Write([]byte("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"))
c.Conn.Write([]byte("Origin: http://" + host + "\r\n"))
c.Conn.Write([]byte("Sec-WebSocket-Key: w4v7O6xFTi36lq3RNcgctw==\r\n"))
c.Conn.Write([]byte("Sec-WebSocket-Protocol: binary\r\n"))
c.Conn.Write([]byte("Sec-WebSocket-Version: 13\r\n"))
c.Conn.Write([]byte("\r\n"))
@@ -69,17 +58,18 @@ func (c *Conn) Handshake() error {
return errors.New("error in ws handshake")
}
respHeader, err := tpr.ReadMIMEHeader()
if err != nil {
return err
}
// respHeader, err := tpr.ReadMIMEHeader()
// if err != nil {
// return err
// }
// TODO: verify this
respHeader.Get("Sec-WebSocket-Accept")
// // TODO: verify this
// respHeader.Get("Sec-WebSocket-Accept")
// fmt.Printf("respHeader: %+v\n", respHeader)
return nil
}
func (c *Conn) Write(b []byte) (n int, err error) {
if c.writer == nil {
c.writer = FrameWriter(c.Conn)
@@ -87,6 +77,7 @@ func (c *Conn) Write(b []byte) (n int, err error) {
return c.writer.Write(b)
}
func (c *Conn) Read(b []byte) (n int, err error) {
if c.reader == nil {
c.reader = FrameReader(c.Conn)