func newClientConnection(connectionUrl string) (conn *websocket.Conn) {
	u, err := url.Parse(connectionUrl)
	if err != nil {
		Error.Println(err)
	}

	Trace.Printf("url for new client connection is %+v\n", u)

	Info.Println("Attempting to dial " + u.Host)

	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		Error.Printf("Failed to dial %s. Error: %+v\n", err)
		return nil
	}

	wsHeaders := http.Header{
		"Origin": {u.Host},
		// your milage may differ
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Error.Printf("websocket.NewClient Error: %s\nResp:%+v", err, resp)
	}

	Info.Printf("Successfully connected to %+v", wsConn.RemoteAddr())

	return wsConn
}
Example #2
0
func (c *ContainerConnection) openSocketToContainer() error {
	id := c.id
	endpoint := GlobalConfig.GetDockerEndpoint()
	u, err := url.Parse(endpoint + "/v" + DockerApiVersion + "/containers/" + id + "/attach/ws?logs=0&stderr=1&stdout=1&stream=1&stdin=1")
	if err != nil {
		return err
	}

	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		return err
	}

	wsHeaders := http.Header{
		"Origin": {"http://localhost:4500"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Log.Error("Unable to connect", resp, err)
	}
	c.container = wsConn
	return err
}
Example #3
0
func (b BackendController) NewWebsocket(connectionUrl string) (*websocket.Conn, error) {
	u, err := url.Parse(connectionUrl)
	if err != nil {
		log.Println(err)
		return nil, errors.New("Cannot parse connection url" + connectionUrl)
	}
	log.Println(u)

	log.Println(u.Host)
	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		log.Println(err)
		return nil, errors.New("cannot dial " + u.Host)
	}

	wsHeaders := http.Header{
		"Origin": {u.Host},
		// your milage may differ
		"Sec-WebSocket-Extensions": {
			"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {

		return nil, fmt.Errorf("websocket.NewClient Error: %s\nResp:%+v", err, resp)

	}

	b.AddNewConnection(wsConn)

	return wsConn, nil
}
Example #4
0
func NewClient(originURL, targetURL string, settings map[string]interface{}) (c *websocket.Conn, response *http.Response, err error) {
	u, err := url.Parse(targetURL)
	if err != nil {
		return nil, nil, err
	}

	dialer := net.Dialer{}

	timeoutInterface, ok := settings["Timeout"]
	if ok {
		dialer.Timeout = timeoutInterface.(time.Duration)
	}

	keepAliveInterface, ok := settings["KeepAlive"]
	if ok {
		dialer.KeepAlive = keepAliveInterface.(time.Duration)
	}

	rawConn, err := dialer.Dial("tcp", u.Host)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"Error": err.Error(),
		}).Errorf("TCP connection error when dialing %v", u.Host)

		return nil, nil, err
	}

	wsHeaders := http.Header{
		"Origin": {originURL},
		// your milage may differ
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	return websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)
}
Example #5
0
func (wi *websocketInstance) connect() {
	//keep trying to get a connection

	var conn net.Conn
	var dialConnection func()
	dialConnection = func() {
		_conn, err := net.Dial("tcp", wi.address+":"+wi.port)
		if err != nil {
			defer dialConnection()
			time.Sleep(pingPeriod)
			return
		}
		conn = _conn
	}
	dialConnection()

	log.Println("connection found")

	site, err := url.Parse("ws://" + wi.address + ":" + wi.port + wi.path)

	wi.socket, _, err = websocket.NewClient(conn, site, nil, bufferSize, bufferSize)

	if err != nil {
		if _, ok := err.(websocket.HandshakeError); !ok {
			log.Println(err)
		}
		return
	}

	go wi.writeHandler()
	go wi.readHandler()
}
Example #6
0
func (ws *WSConnection) connectOnce(r *Room, try int) error {
	r.Logger.Infof("Connecting to room %s...", r.RoomName)
	tlsConn, err := tls.Dial("tcp", "euphoria.io:443", &tls.Config{})
	if err != nil {
		return err
	}
	roomURL, err := url.Parse(fmt.Sprintf("wss://euphoria.io/room/%s/ws", r.RoomName))
	if err != nil {
		return err
	}
	wsConn, _, err := websocket.NewClient(tlsConn, roomURL, http.Header{}, 4096, 4096)
	if err != nil {
		return err
	}
	if err := r.Ctx.Check("connectOnce", try); err != nil {
		return err
	}
	ws.conn = wsConn
	if r.password != "" {
		if _, err := r.sendAuth(); err != nil {
			return err
		}
	}
	if _, err := r.sendNick(); err != nil {
		return err
	}
	return nil
}
Example #7
0
func (c *GremlinClient) Connect() {
	host := c.Addr + ":" + strconv.FormatInt(int64(c.Port), 10)

	conn, err := net.Dial("tcp", host)
	if err != nil {
		logging.GetLogger().Error("Connection to the WebSocket server failed: %s", err.Error())
		return
	}

	endpoint := "ws://" + host
	u, err := url.Parse(endpoint)
	if err != nil {
		logging.GetLogger().Error("Unable to parse the WebSocket Endpoint %s: %s", endpoint, err.Error())
		return
	}

	wsConn, _, err := websocket.NewClient(conn, u, http.Header{}, 0, 4096)
	if err != nil {
		logging.GetLogger().Error("Unable to create a WebSocket connection %s : %s", endpoint, err.Error())
		return
	}

	logging.GetLogger().Info("Connected to gremlin server %s:%d", c.Addr, c.Port)

	c.wsConn = wsConn
}
Example #8
0
func TestWebsocketQuery(t *testing.T) {
	w := test.GetWorld(t)
	pn := w.NewPermanode(t)
	test.MustRunCmd(t, w.Cmd("camput", "attr", pn.String(), "tag", "foo"))

	check := func(err error) {
		if err != nil {
			t.Fatal(err)
		}
	}

	const bufSize = 1 << 20

	c, err := net.Dial("tcp", w.Addr())
	if err != nil {
		t.Fatalf("Dial: %v", err)
	}
	defer c.Close()

	wc, _, err := websocket.NewClient(c, &url.URL{Host: w.Addr(), Path: w.SearchHandlerPath() + "ws"}, nil, bufSize, bufSize)
	check(err)

	msg, err := wc.NextWriter(websocket.TextMessage)
	check(err)

	_, err = msg.Write([]byte(`{"tag": "foo", "query": { "expression": "tag:foo" }}`))
	check(err)
	check(msg.Close())

	errc := make(chan error, 1)
	go func() {
		inType, inMsg, err := wc.ReadMessage()
		if err != nil {
			errc <- err
			return
		}
		if !strings.HasPrefix(string(inMsg), `{"tag":"_status"`) {
			errc <- fmt.Errorf("unexpected message type=%d msg=%q, wanted status update", inType, inMsg)
			return
		}
		inType, inMsg, err = wc.ReadMessage()
		if err != nil {
			errc <- err
			return
		}
		if strings.Contains(string(inMsg), pn.String()) {
			errc <- nil
			return
		}
		errc <- fmt.Errorf("unexpected message type=%d msg=%q", inType, inMsg)
	}()
	select {
	case err := <-errc:
		if err != nil {
			t.Error(err)
		}
	case <-time.After(5 * time.Second):
		t.Error("timeout")
	}
}
Example #9
0
func NewConnection(pin string) (*Connection, error) {
	gameId, err := strconv.Atoi(pin)
	if err != nil {
		return nil, err
	}

	conn, err := tls.Dial("tcp", "kahoot.it:443", nil)
	if err != nil {
		return nil, err
	}

	url, _ := url.Parse("wss://kahoot.it/cometd")
	reqHeader := http.Header{}
	reqHeader.Set("Origin", "https://kahoot.it")
	reqHeader.Set("Cookie", "no.mobitroll.session="+pin)
	ws, _, err := websocket.NewClient(conn, url, reqHeader, 100, 100)
	if err != nil {
		return nil, err
	}

	incoming := make(chan incomingData, 100)
	res := &Connection{ws, 0, gameId, "", incoming}
	go res.readLoop()
	return res, nil
}
Example #10
0
// Open WebSocket connection to Kubernetes API server
func openConnection(endpoint string) *websocket.Conn {
	u, err := url.Parse(endpoint)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Connect to K8S master host: %v", u.Host)
	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		log.Fatal(err)
	}

	wsHeaders := http.Header{
		"Origin":                   {endpoint},
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)
	if err != nil {
		log.Fatalf("websocket.NewClient Error: %s\nResp:%+v", err, resp)

	}

	return wsConn
}
Example #11
0
func (c *ContainerConnection) openSocketToContainer() error {
	id := c.id
	endpoint := GlobalConfig.GetDockerEndpoint()
	u, err := url.Parse(endpoint + "/v" + DockerApiVersion + "/containers/" + id + "/attach/ws?logs=0&stderr=1&stdout=1&stream=1&stdin=1")
	if err != nil {
		return err
	}

	var rawConn net.Conn
	if GlobalConfig.DockerServerUseHttps {
		rawConn, err = tls.Dial("tcp", u.Host, GlobalConfig.tlsConfig)
	} else {
		rawConn, err = net.Dial("tcp", u.Host)
	}
	if err != nil {
		return err
	}

	wsHeaders := http.Header{
		"Origin": {endpoint},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Log.Error("Unable to connect", resp, err)
	}
	c.container = wsConn
	return err
}
Example #12
0
func wsClient(conn net.Conn, host string) (*wsConn, error) {
	c, resp, err := websocket.NewClient(conn, &url.URL{Scheme: "ws", Host: host, Path: "/ws"}, nil, 4096, 4096)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	return &wsConn{conn: c}, nil
}
Example #13
0
func connectWebsocketNoHandshake(t *testing.T, server *httptest.Server, header http.Header) (*websocket.Conn, error) {
	conn := connectToTestServer(t, server)
	url := urlMustParse(server.URL)
	url.Path = "/ctrl"
	url.Scheme = "ws"
	ws, _, err := websocket.NewClient(conn, url, header, 1024, 1024)
	if err != nil {
		return nil, fmt.Errorf("raw websocket client: %v", err)
	}
	return ws, nil
}
Example #14
0
func connectWebsocket(server *httptest.Server, path string) (*websocket.Conn, error) {
	conn, err := connectToTestServer(server)
	if err != nil {
		return nil, err
	}
	url := urlMustParse(server.URL + path)
	ws, _, err := websocket.NewClient(conn, url, nil, 1024, 1024)
	if err != nil {
		return nil, err
	}
	return ws, nil
}
Example #15
0
func newClient() (*websocket.Conn, error) {
	u, _ := url.Parse(WSURL)
	conn, err := net.Dial("tcp", ADDR)

	if err != nil {
		return nil, err
	}

	header := http.Header{"Origin": {ORIGIN}}
	ws, _, err := websocket.NewClient(conn, u, header, 1024, 1024)
	return ws, err
}
Example #16
0
func startClient() {
	fmt.Println("start...")
	// rcount = 0
	// scount = 0
	url, err := url.Parse("http://localhost:4000/")
	if err != nil {
		fmt.Println("url parse failed")
		fmt.Println(err.Error())
		return
	}

	conn, err := net.Dial("tcp", url.Host)
	if err != nil {
		fmt.Println("dial failed")
		fmt.Println(err.Error())
		return
	}
	if conn == nil {
		fmt.Println("Conn nil")
	}

	requestHeader := http.Header{
		"Origin":                   {"http://localhost:4000"},
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, response, err := websocket.NewClient(conn, url, requestHeader, 1024, 1024)
	if err != nil {
		fmt.Println("newClient failed")
		fmt.Println(response)
		fmt.Println(err.Error())
	}
	// fmt.Println("Creating Channels")
	recd := make(chan []byte, 1)
	quit := make(chan bool, 2)

	wsConn.WriteMessage(websocket.TextMessage, []byte("Hey"))
	// scount++
	// fmt.Printf("s: %d\n", scount)

	addReadListener(recd, quit)
	sendHeartbeats(wsConn)

	for {
		_, received, err := wsConn.ReadMessage()
		if err != nil {
			fmt.Println("read failed")
			fmt.Println(err.Error())
			break
		}
		recd <- received
	}
}
Example #17
0
func (self *ClientWebsocket) connect() (ws *websocket.Conn, e error) {
	c, e := net.Dial("tcp", self.url.Host)
	if e != nil {
		return nil, fmt.Errorf("net.Dial failed: %s", e.Error())
	}

	ws, _, e = websocket.NewClient(c, self.url, *self.httpHeader, 1024, 1024)
	if e != nil {
		return nil, fmt.Errorf("websocket.NewClient failed: %s", e)
	}

	return ws, nil
}
Example #18
0
// Connect opens a connection to the backend and upgrades it to a websocket. Calls to
// 'MakeRequest' can be made after calling this, but responss will not be
// receivable until 'Serve' is also called.
func (cs *ClientServerImpl) Connect() error {
	parsedURL, err := url.Parse(cs.URL)
	if err != nil {
		return err
	}

	// NewRequest never returns an error if the url parses and we just verified
	// it did above
	request, _ := http.NewRequest("GET", cs.URL, nil)
	// Sign the request; we'll send its headers via the websocket client which includes the signature
	utils.SignHTTPRequest(request, cs.Region, ServiceName, cs.CredentialProvider)

	// url.Host might not have the port, but tls.Dial needs it
	dialHost := parsedURL.Host
	if !strings.Contains(dialHost, ":") {
		dialHost += ":443"
	}

	timeoutDialer := &net.Dialer{Timeout: wsConnectTimeout}
	log.Info("Creating poll dialer", "host", parsedURL.Host)
	wsConn, err := tls.DialWithDialer(timeoutDialer, "tcp", dialHost, &tls.Config{InsecureSkipVerify: cs.AcceptInvalidCert})
	if err != nil {
		return err
	}

	websocketConn, httpResponse, err := websocket.NewClient(wsConn, parsedURL, request.Header, readBufSize, writeBufSize)
	if httpResponse != nil {
		defer httpResponse.Body.Close()
	}
	if err != nil {
		defer wsConn.Close()
		var resp []byte
		if httpResponse != nil {
			var readErr error
			resp, readErr = ioutil.ReadAll(httpResponse.Body)
			if readErr != nil {
				return errors.New("Unable to read websocket connection: " + readErr.Error() + ", " + err.Error())
			}
			// If there's a response, we can try to unmarshal it into one of the
			// modeled error types
			possibleError, _, decodeErr := DecodeData(resp, cs.TypeDecoder)
			if decodeErr == nil {
				return cs.NewError(possibleError)
			}
		}
		log.Warn("Error creating a websocket client", "err", err)
		return errors.New(string(resp) + ", " + err.Error())
	}
	cs.Conn = websocketConn
	return nil
}
Example #19
0
// Handles incoming requests.
func handleRequest(conn net.Conn, rhost string) {
	fmt.Println("TCP connection received")
	defer func() { fmt.Println("Connection closed") }()
	defer conn.Close()

	ws_url, err := url.Parse(rhost)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	wsConn, err := net.Dial(CONN_TYPE, ws_url.Host)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer wsConn.Close()

	REQUEST_HEADERS := map[string][]string{
		"Sec-Websocket-Protocol": []string{"binary", "base64"},
	}
	ws, response, err := websocket.NewClient(wsConn, ws_url, REQUEST_HEADERS, BUFFER_SIZE, BUFFER_SIZE)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer ws.Close()

	protocol_arr := response.Header["Sec-Websocket-Protocol"]
	var protocol string
	if len(protocol_arr) > 0 {
		protocol = protocol_arr[0]
	}

	var messageType int
	if protocol == "base64" {
		messageType = websocket.TextMessage
	} else if protocol == "binary" {
		messageType = websocket.BinaryMessage
	} else {
		fmt.Println("Expected Sec-Websocket-Protocol header value of binary or base64, got:")
		fmt.Println(response.Header)
		return
	}

	fmt.Println("Websocket connection established, proxying...")
	var stopChan = make(chan int)
	go pipe_to_ws(conn, ws, messageType, stopChan)
	pipe_to_net(conn, ws, messageType, stopChan)
}
Example #20
0
func StartAgent(pURL *url.URL, subdomain, serverAddr string, remoteListenPort int, data string) {
	log.Debug("start proxy", pURL)
	if !regexp.MustCompile("^http[s]://").MatchString(serverAddr) {
		serverAddr = "http://" + serverAddr
	}
	sURL, err := url.Parse(serverAddr)
	if err != nil {
		log.Fatal(err)
	}

	sURL.Path = "/ws"
	log.Debug("server host:", sURL.Host)
	conn, err := net.Dial("tcp", sURL.Host)
	if err != nil {
		log.Fatal(err)
	}
	// specify remote listen port
	sURL.Scheme = "ws"
	query := sURL.Query()
	query.Add("protocol", pURL.Scheme)
	query.Add("subdomain", subdomain)
	query.Add("data", data)
	if remoteListenPort != 0 {
		query.Add("port", strconv.Itoa(remoteListenPort))
	}
	sURL.RawQuery = query.Encode()

	log.Debug(sURL)
	wsclient, _, err := websocket.NewClient(conn, sURL, nil, 1024, 1024)
	if err != nil {
		log.Fatal(err)
	}
	defer wsclient.Close()
	go idleWsSend(wsclient)

	for {
		var msg Msg
		if err := wsclient.ReadJSON(&msg); err != nil {
			fmt.Println("client exit: " + err.Error())
			break
		}
		log.Debug("recv:", msg)

		// sURL: serverURL
		rnl := NewRevNetListener()
		go handleRevConn(pURL, rnl)
		handleWsMsg(msg, sURL, rnl)
	}
}
Example #21
0
func wssClient(conn net.Conn, host string) (*wsConn, error) {
	tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
	if err := tlsConn.Handshake(); err != nil {
		return nil, err
	}
	conn = tlsConn

	c, resp, err := websocket.NewClient(conn, &url.URL{Scheme: "wss", Host: host, Path: "/ws"}, nil, 4096, 4096)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	return &wsConn{conn: c}, nil
}
Example #22
0
// This is a immediately return function
func (c *Client) RunProxy(opts ProxyOptions) (pc *ProxyConnector, err error) {
	if opts.Proto == "" {
		return nil, ErrPrototolRequired
	}
	q := c.sURL.Query()
	q.Add("protocol", string(opts.Proto))
	q.Add("subdomain", opts.Subdomain)
	q.Add("data", opts.ExtraData)
	if opts.ListenPort != 0 {
		q.Add("port", strconv.Itoa(opts.ListenPort))
	}
	c.sURL.RawQuery = q.Encode()

	conn, err := net.Dial("tcp", c.sURL.Host)
	if err != nil {
		return nil, ErrDialTCP
	}
	wsclient, _, err := websocket.NewClient(conn, c.sURL, nil, 1024, 1024)
	if err != nil {
		return nil, err
	}
	pc = &ProxyConnector{wsConn: wsclient}
	var msg message
	if err := wsclient.ReadJSON(&msg); err != nil {
		return nil, err
	}
	pc.remoteAddr = msg.Body

	pc.wg.Add(1)
	go idleWsSend(wsclient) // keep websocket alive to prevent nginx timeout issue
	go func() {
		defer wsclient.Close()
		revListener := newRevNetListener()
		defer revListener.Close()
		defer pc.wg.Done()

		go serveRevConn(opts.Proto, opts.LocalAddr, revListener)
		for {
			if err := wsclient.ReadJSON(&msg); err != nil {
				pc.err = err
				return
			}
			go handleWsMsg(msg, c.sURL, revListener) // send new conn to rnl
		}
	}()
	return pc, nil
}
Example #23
0
func connect(cid int, wg *sync.WaitGroup) {
	conn, err := net.Dial("tcp", "127.0.0.1:4000")
	if err != nil {
		fmt.Println(err)
		return
	}
	u, err := url.Parse("http://127.0.0.1:4000/foobar")
	if err != nil {
		fmt.Println(err)
		return
	}
	h := &http.Header{}
	h.Add("Origin", "localhost:4000")
	sc, _, err := websocket.NewClient(conn, u, *h, 0, 0)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer sc.Close()
	var mid = 0
	for {
		time.Sleep(1 * time.Nanosecond)
		if err = sc.WriteMessage(1, []byte("Hello from client")); err != nil {
			fmt.Println(err)
			return
		}
		_, p, err := sc.ReadMessage()
		if err != nil {
			fmt.Println(err)
			return
		}
		//m.Lock()
		sout := bytes.NewBuffer(make([]byte, 0))
		fmt.Fprintf(sout, "[c-%v][m-%v] RCVD:", cid, mid)
		fmt.Fprintf(sout, "%v\n", string(p))
		//m.Unlock()
		ioutil.WriteFile(fmt.Sprintf("results/%v.%v", cid, mid), sout.Bytes(), os.ModePerm)
		mid++
		if mid == 100 {
			return
		}
	}
	time.Sleep(5 * time.Second)
	// sout.Flush()
	time.Sleep(5 * time.Second)
	wg.Done()
}
Example #24
0
func (s *Session) connectOnce() error {
	s.logger.Debugln("Connecting to euphoria via TLS...")
	tlsConn, err := tls.Dial("tcp", "euphoria.io:443", &tls.Config{})
	if err != nil {
		s.logger.Warningln("Connection via TLS failed.")
		return err
	}
	roomURL, _ := url.Parse(fmt.Sprintf("wss://euphoria.io/room/%s/ws", s.RoomName))
	wsConn, _, err := websocket.NewClient(tlsConn, roomURL, http.Header{}, 4096, 4096)
	if err != nil {
		s.logger.Warningln("Upgrade of TLS connection to websocket failed.")
		return err
	}
	s.conn = wsConn
	s.logger.Debugln("Connection complete.")
	return nil
}
Example #25
0
func makeTunnel() (c net.Conn, err error) {
	if UseTLS || UseWebsocket || !UseHttp {
		c, err = connect(Saddr)
	} else {
		addr := Saddr
		if proxyURL != nil {
			addr = proxyURL.Host
		}
		c, err = dial(addr)
	}
	if err != nil {
		return
	}

	if UseTLS {
		config := &tls.Config{InsecureSkipVerify: true}
		c = tls.Client(c, config)
	} else if UseWebsocket {
		ws, resp, err := websocket.NewClient(c, &url.URL{Host: Saddr}, nil, 8192, 8192)
		if err != nil {
			c.Close()
			return nil, err
		}
		resp.Body.Close()

		c = NewWSConn(ws)
	} else if UseHttp {
		httpcli := NewHttpClientConn(c)
		if err = httpcli.Handshake(); err != nil {
			c.Close()
			return nil, err
		}
		c = httpcli
		//defer httpcli.Close()
	}

	sc := gosocks5.ClientConn(c, clientConfig)
	if err = sc.Handleshake(); err != nil {
		c.Close()
		return nil, err
	}
	c = sc

	return
}
Example #26
0
func wrapWS(c io.Closer, info *MethodInfo) (io.Closer, error) {
	hdrs, ok := info.Pragma["ws-headers"].(http.Header)
	if !ok {
		hdrs = http.Header{}
	}

	co, ok := c.(net.Conn)
	if !ok {
		return nil, fmt.Errorf("Websocket requires net.Conn")
	}

	conn, res, err := websocket.NewClient(co, info.URL, hdrs, 0, 0)
	if err != nil {
		return nil, err
	}

	return NewWSFrameAdaptor(conn, nil, res), nil
}
Example #27
0
// Connect opens a connection to the backend and upgrades it to a websocket. Calls to
// 'MakeRequest' can be made after calling this, but responss will not be
// receivable until 'Serve' is also called.
func (cs *ClientServerImpl) Connect() error {
	parsedURL, err := url.Parse(cs.URL)
	if err != nil {
		return err
	}

	// NewRequest never returns an error if the url parses and we just verified
	// it did above
	request, _ := http.NewRequest("GET", cs.URL, nil)
	// Sign the request; we'll send its headers via the websocket client which includes the signature
	utils.SignHTTPRequest(request, cs.Region, ServiceName, cs.CredentialProvider, nil)

	wsConn, err := cs.websocketConn(parsedURL, request)
	if err != nil {
		return err
	}

	websocketConn, httpResponse, err := websocket.NewClient(wsConn, parsedURL, request.Header, readBufSize, writeBufSize)
	if httpResponse != nil {
		defer httpResponse.Body.Close()
	}
	if err != nil {
		defer wsConn.Close()
		var resp []byte
		if httpResponse != nil {
			var readErr error
			resp, readErr = ioutil.ReadAll(httpResponse.Body)
			if readErr != nil {
				return errors.New("Unable to read websocket connection: " + readErr.Error() + ", " + err.Error())
			}
			// If there's a response, we can try to unmarshal it into one of the
			// modeled error types
			possibleError, _, decodeErr := DecodeData(resp, cs.TypeDecoder)
			if decodeErr == nil {
				return cs.NewError(possibleError)
			}
		}
		log.Warn("Error creating a websocket client", "err", err)
		return errors.New(string(resp) + ", " + err.Error())
	}
	cs.Conn = websocketConn
	return nil
}
func TestClientServer(t *testing.T) {
	s := httptest.NewServer(wsHandler{t})
	defer s.Close()
	u, _ := url.Parse(s.URL)
	c, err := net.Dial("tcp", u.Host)
	if err != nil {
		t.Fatalf("Dial: %v", err)
	}
	ws, resp, err := websocket.NewClient(c, u, http.Header{"Origin": {s.URL}}, 1024, 1024)
	if err != nil {
		t.Fatalf("NewClient: %v", err)
	}
	defer ws.Close()

	var sessionID string
	for _, c := range resp.Cookies() {
		if c.Name == "sessionID" {
			sessionID = c.Value
		}
	}
	if sessionID != "1234" {
		t.Error("Set-Cookie not received from the server.")
	}

	w, _ := ws.NextWriter(websocket.TextMessage)
	io.WriteString(w, "HELLO")
	w.Close()
	ws.SetReadDeadline(time.Now().Add(1 * time.Second))
	op, r, err := ws.NextReader()
	if err != nil {
		t.Fatalf("NextReader: %v", err)
	}
	if op != websocket.TextMessage {
		t.Fatalf("op=%d, want %d", op, websocket.TextMessage)
	}
	b, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatalf("ReadAll: %v", err)
	}
	if string(b) != "HELLO" {
		t.Fatalf("message=%s, want %s", b, "HELLO")
	}
}
Example #29
0
func newClient() (*websocket.Conn, error) {
	conn, err := net.Dial("tcp", "127.0.0.1:58081")
	if err != nil {
		return nil, err
	}

	endpoint := "ws://127.0.0.1:58081/ws/graph"
	u, err := url.Parse(endpoint)
	if err != nil {
		return nil, err
	}

	wsConn, _, err := websocket.NewClient(conn, u, http.Header{"Origin": {endpoint}}, 1024, 1024)
	if err != nil {
		return nil, err
	}

	return wsConn, nil
}
Example #30
0
func postHandler(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path[8:]
	log.Println("New", path, "request")
	body, _ := ioutil.ReadAll(r.Body)

	gm := GenericMessage{}
	json.Unmarshal(body, &gm)
	trainer_id := gm.Trainer
	if _, ok := connections[trainer_id]; !ok {
		HttpConn, _ := net.Dial("tcp", "127.0.0.1:10914")
		ws, _, _ := websocket.NewClient(HttpConn, server_url, r.Header, 4096, 4096)
		conn := &Connection{
			ws:   ws,
			last: make(chan []byte),
			send: make(chan []byte),
		}
		go conn.Reader()
		go conn.Writer()
		connections[trainer_id] = conn
	}
	conn := connections[trainer_id]

	if path == "initialize" {
		conn.send <- body
	} else if path == "attack" {
		amsg := AttackMessage{}
		json.Unmarshal(body, &amsg)
		jmsg, _ := json.Marshal(amsg)
		conn.send <- jmsg
	} else if path == "switch" {
		smsg := SwitchMessage{}
		json.Unmarshal(body, &smsg)
		jmsg, _ := json.Marshal(smsg)
		conn.send <- jmsg
	} else {
		return
	}

	response := <-conn.last
	fmt.Fprintf(w, string(response))
	log.Println("Sent ", string(response))
}