package main
import (
"bufio"
"fmt"
"net"
"net/http"
wshttp "wsserv/wshttp"
"github.com/gorilla/websocket"
)
const (
flagHost = "host"
flagPort = "port"
defHost = "localhost"
defPort = 8070
defBufSiz = 256
)
var (
port int = 8070
stream bool
)
func acceptTcpCon(addr string) (net.Conn, error) {
var (
err error
l net.Listener
)
if l, err = net.Listen("tcp", addr); err != nil {
return nil, err
}
return l.Accept()
}
func acceptWsCon(tCon net.Conn) *websocket.Conn {
var (
err error
req *http.Request
con *websocket.Conn
r = bufio.NewReader(tCon)
rw = wshttp.NewResponse(tCon)
)
for con == nil {
if req, err = http.ReadRequest(r); err != nil {
http.Error(rw, fmt.Sprintf("error: unable to read request: %v", err), http.StatusBadRequest)
continue
}
if con, err = websocket.Upgrade(rw, req, nil, defBufSiz, defBufSiz); err != nil {
http.Error(rw, fmt.Sprintf("error: unable to create websocket connection: %v", err), http.StatusBadRequest)
}
}
return con
}
func main() {
var (
err error
tCon net.Conn
con *websocket.Conn
listenAddr = fmt.Sprintf("%s:%d", defHost, port)
)
logInfo.Printf("listening on '%s'", listenAddr)
if tCon, err = acceptTcpCon(listenAddr); err != nil {
panic(err)
}
con = acceptWsCon(tCon)
fmt.Println(con.WriteMessage(websocket.TextMessage, []byte("hellooooooo\n")))
}