func handleConnection(conn *net.TCPConn) error { defer conn.Close() handlerChan <- 1 defer func() { handlerChan <- -1 }() var ws *websocket.Conn conn.SetDeadline(time.Now().Add(socksTimeout)) err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) { // Disable deadline. conn.SetDeadline(time.Time{}) Log("SOCKS request for %s", dest) destAddr, err := net.ResolveTCPAddr("tcp", dest) if err != nil { return nil, err } wsUrl := url.URL{Scheme: "ws", Host: dest} ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String()) if err != nil { return nil, err } Log("WebSocket connection to %s", ws.Config().Location.String()) return destAddr, nil }) if err != nil { return err } defer ws.Close() proxy(conn, ws) return nil }
//Handeler for websocket connectionf from client pages. Expects a []int list of feature id's as its first message //and will submit these tasks and then wait to stream results back func SocketStreamer(ws *websocket.Conn) { fmt.Printf("jsonServer %#v\n", ws.Config()) //for { url := *ws.Config().Location id := UniqueId() url.Scheme = "http" url.Path = "/results/" + id var msg []int err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println(err) //break } //TODO:Consider allowing multiple tasks submissions on one channel instead of only waiting for one msg fmt.Printf("recv:%#v\n", msg) RestultChan := make(chan string, 0) WsRegistry[id] = RestultChan SubmitTasks(msg, url.String()) for { msg := <-RestultChan err = websocket.Message.Send(ws, msg) if err != nil { fmt.Println(err) break } fmt.Printf("send:%#v\n", msg) } //TODO: remove ws from registry and cancel outstandign jobs when connetion dies }
//wsHandler now used ws.Config as protocol handshake now supported func wsHandler(ws *websocket.Conn) { defer flow.DontPanic() defer ws.Close() hdr := ws.Request().Header // keep track of connected clients for reload broadcasting id := hdr.Get("Sec-Websocket-Key") wsClients[id] = ws defer delete(wsClients, id) // the protocol name is used as tag to locate the proper circuit //lightbulb: We use the protocol provided by ws, rather than header, as that contains server accepted value tag := ws.Config().Protocol[0] fmt.Println("WS Protocol Selected:", tag) if tag == "" { //no specific protocol, lets opt for 'default' which just echoes (or return with no circuit!) tag = "default" } g := flow.NewCircuit() g.AddCircuitry("head", &wsHead{ws: ws}) g.Add("ws", "WebSocket-"+tag) //the client has negotiated this support g.AddCircuitry("tail", &wsTail{ws: ws}) g.Connect("head.Out", "ws.In", 0) g.Connect("ws.Out", "tail.In", 0) g.Run() }
//handle a websocket connection received from webserver func jsonServer(ws *websocket.Conn) { fmt.Printf("jsonServer %#v\n", ws.Config()) for { var msg T // Receive receives a text message serialized T as JSON. err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println(err) break } fmt.Printf("recv:%#v\n", msg) // Send send a text message serialized T as JSON. msg.Msg = "pong" msg.Tps = stackLastTps.Pop().(int) // Send to the webclients err = websocket.JSON.Send(ws, msg) if err != nil { fmt.Println(err) break } fmt.Printf("send:%#v\n", msg) } }
// WSCompileRunHandler handles the websocket connection for a given compile/run action. // It handles transcoding Messages to and from JSON format, and handles starting // and killing processes. func WSCompileRunHandler(c *websocket.Conn) { c.Config() in, out := make(chan *Message), make(chan *Message) errc := make(chan error, 1) // Decode messages from client and send to the in channel. go func() { dec := json.NewDecoder(c) for { var m Message if err := dec.Decode(&m); err != nil { fmt.Printf("error in dec.Decode %s\n", err) errc <- err return } in <- &m } }() // Receive messages from the out channel and encode to the client. go func() { enc := json.NewEncoder(c) for m := range out { if err := enc.Encode(m); err != nil { fmt.Printf("error in enc.Encode %s\n", err) errc <- err return } } }() // Start and kill Processes and handle errors. proc := make(map[string]*Process) for { select { case m := <-in: switch m.Kind { case "run": goTest := m.GoTest proc[m.Id].Kill() if goTest { proc[m.Id] = StartTest(m.Id, m.SrcDir, m.RunOpts, nil, out) } else { proc[m.Id] = StartProcess(m.Id, m.Body, m.BuildOpts, m.RunOpts, nil, out) } case "kill": proc[m.Id].Kill() } case err := <-errc: // A encode or decode has failed; bail. log.Println(err) // Shut down any running processes. for _, p := range proc { p.Kill() } return } } }
func wsHandler(ws *websocket.Conn) { fmt.Println("NEW WEBSOCKET!") fmt.Println(ws.Config()) fmt.Println(ws.RemoteAddr()) c := &connection{send: make(chan string, 256), ws: ws} go c.writer() c.reader() }
func wsHandler(ws *websocket.Conn) { c := &client{ ws: ws, origin: ws.Config().Origin.String(), SendChan: make(chan interface{}, 5), RecvChan: make(chan interface{}, 5), } internalClientConnectChan <- c defer func() { ClientRmChan <- c ClientDisconnectChan <- c }() go c.send() c.recv() }
func socketHandler(ws *websocket.Conn) { loc := ws.Config().Location.String() var id string websocket.Message.Receive(ws, &id) s := socket{ws, make(chan bool), loc, id} checkingSocketMap.Lock() if _, exist := socketmap[loc]; !exist { socketmap[loc] = make(chan socket) } checkingSocketMap.Unlock() go match(s) <-s.done fmt.Println("[ws] closing connection to " + id + " on channel " + loc) }
// cmdServer handles a json string sent from client using websocket.JSON. func cmdServer(ws *websocket.Conn) { fmt.Printf("cmdServer %#v\n", ws.Config()) defer ws.Close() for { var msg T // Receive receives a text message serialized T as JSON. err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println(err) break } fmt.Printf("recv:%#v\n", msg) switch msg.Tag { case "init": sclangObj, err = sclang.Start(PathToSclang, &WebSocketWriter{ws}) //sclangObj, err = sclang.Start(PathToSclang, os.Stdout) case "start_server": err = sclangObj.StartServer() case "stop_server": err = sclangObj.StopServer() case "evaluate": err = sclangObj.Evaluate(msg.Value, false) case "stop_sound": err = sclangObj.StopSound() case "toggle_recording": err = sclangObj.ToggleRecording() case "restart_interpreter": err = sclangObj.Restart() } if err != nil { fmt.Println(err) break } // Send send a text message serialized T as JSON. err = websocket.JSON.Send(ws, msg) if err != nil { fmt.Println(err) break } fmt.Printf("send:%#v\n", msg) } }
func socketHandler(ws *websocket.Conn) { fmt.Printf("readWriteServer %#v\n", ws.Config()) clientListEl := clients.PushBack(ws) for { buf := make([]byte, 100) n, err := ws.Read(buf) if err != nil { fmt.Println(err) break } go handleMessage(buf[:n], ws) } clients.Remove(clientListEl) fmt.Println("readWriteServer finished") }
// jsonServer echoes back json string sent from client using websocket.JSON. func jsonServer(ws *websocket.Conn) { fmt.Printf("jsonServer %#v\n", ws.Config()) for { var msg T // Receive receives a text message serialized T as JSON. err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println(err) break } fmt.Printf("recv:%#v\n", msg) // Send send a text message serialized T as JSON. err = websocket.JSON.Send(ws, msg) if err != nil { fmt.Println(err) break } fmt.Printf("send:%#v\n", msg) } }
func linewise(down *websocket.Conn, up net.Conn) { params, _ := url.ParseQuery(down.Config().Location.RawQuery) lineEnding := *LineEnding if val := params.Get("lineEnding"); val != "" { lineEnding = val } exit := make(chan bool) go func() { io.Copy(down, up); exit <- true }() go func() { for { var msg string if rerr := websocket.Message.Receive(down, &msg); rerr != nil { break } if _, werr := up.Write([]byte(msg + lineEnding)); werr != nil { break } } exit <- true }() <-exit }
func echo(ws *websocket.Conn) { fmt.Printf("echo %#v\n", ws.Config()) for n := 0; n < 10; n++ { msg := "Hello " + string(n+48) fmt.Println("Sending to client: " + msg) err := websocket.Message.Send(ws, msg) if err != nil { fmt.Println("Cannot send") break } var reply string err = websocket.Message.Receive(ws, &reply) if err != nil { fmt.Println("Cannot receive") break } fmt.Println("Received back from client: " + reply) } fmt.Println("echo finished") }
// readWriteServer echoes back messages sent from client using Read and Write. func readWriteServer(ws *websocket.Conn) { fmt.Printf("readWriteServer %#v\n", ws.Config()) for { buf := make([]byte, 100) // Read at most 100 bytes. If client sends a message more than // 100 bytes, first Read just reads first 100 bytes. // Next Read will read next at most 100 bytes. n, err := ws.Read(buf) if err != nil { fmt.Println(err) break } fmt.Printf("recv:%q\n", buf[:n]) // Write send a message to the client. n, err = ws.Write(buf[:n]) if err != nil { fmt.Println(err) break } fmt.Printf("send:%q\n", buf[:n]) } fmt.Println("readWriteServer finished") }
// jsonServer echoes back json string sent from client using websocket.JSON func jsonServer(ws *websocket.Conn) { fmt.Printf("jsonServer %#v\n", ws.Config()) for { var msg T // Receive receives a text message serialized T as JSON err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("recv:%#v\n", msg) switch msg.Msg { case "getpids": //p := &pids { GetPids(), } msg.Msg = GetPids() //out, err := json.Marshal(p) //if err != nil { // fmt.Println("Marshal:", err) // os.Exit(1) //} //fmt.Printf("%v - %v\n", out, p) //os.Exit(1) //msg.Msg = fmt.Sprintf("%#v", p) //msg.Msg = string(p) } // Send sends a text message serialized T as JSON err = websocket.JSON.Send(ws, msg) if err != nil { fmt.Println(err) os.Exit(1) } //fmt.Printf("send:%#v\n", msg) } }
// copyServer echoes back messages sent from client using io.Copy. func copyServer(ws *websocket.Conn) { fmt.Printf("copyServer %#v\n", ws.Config()) io.Copy(ws, ws) fmt.Println("copyServer finished") }
/** * Handler for the websocket json server */ func echoJsonServer(ws *websocket.Conn) { fmt.Printf("jsonServer %#v\n", ws.Config()) serveClient(ws, requestQueue, responseQueue) }