func (l *listener) handler(ws *websocket.Conn) { l.lock.Lock() if !l.running { ws.Close() l.lock.Unlock() return } w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true} w.iswss = l.iswss req := ws.Request() w.props = make(map[string]interface{}) w.props[mangos.PropLocalAddr] = ws.LocalAddr() w.props[mangos.PropRemoteAddr], _ = net.ResolveTCPAddr("tcp", req.RemoteAddr) if l.iswss { w.props[mangos.PropTlsConnState] = *req.TLS } w.wg.Add(1) l.pending = append(l.pending, w) l.cv.Broadcast() l.lock.Unlock() // We must not return before the socket is closed, because // our caller will close the websocket on our return. w.wg.Wait() }
func serveWebsocket(conn *websocket.Conn) { var ( // ip addr lAddr = conn.LocalAddr() rAddr = conn.RemoteAddr() // timer tr = DefaultServer.round.Timer(rand.Int()) ) log.Debug("start websocket serve \"%s\" with \"%s\"", lAddr, rAddr) DefaultServer.serveWebsocket(conn, tr) }
func EchoServer(ws *websocket.Conn) { addr := ws.LocalAddr().String() pfx := []byte("[" + addr + "] ") log.Printf("ws connect on %s", addr) // the following could be done with io.Copy(ws, ws) // but I want to add some meta data var msg = make([]byte, 1024) for { n, err := ws.Read(msg) if err != nil && err != io.EOF { log.Printf("ws error on %s. %s", addr, err) break } _, err = ws.Write(append(pfx, msg[:n]...)) if err != nil && err != io.EOF { log.Printf("ws error on %s. %s", addr, err) break } } log.Printf("ws disconnect on %s", addr) }
func wsHandler(ws *websocket.Conn) { done := make(chan bool) raw := make([]byte, 1024) n, err := ws.Read(raw) if err != nil { log(err) return } var address string err = json.Unmarshal(raw[:n], &address) if err != nil { log(err, string(raw[:n])) } registerSocket <- socket{ws, address, done, ws.LocalAddr().String()} go incomingMessageReader(ws) // when this function finishes the socket will be closed <-done ws.Close() }
func GWMockServer(ws *websocket.Conn) { d, _ := strconv.Atoi(os.Args[1]) DELAY := time.Duration(d) logger := new(Logger) logger.Print("Connection from %s", ws.LocalAddr().String()) elements := make([]string, 0) counter := 0 var request interface{} var response *Response for { // Receive request err := websocket.JSON.Receive(ws, &request) if err != nil { break // EOF } req := request.(map[string]interface{}) logger.SetPrefix("* ") m, _ := json.Marshal(request) logger.Print("Received message: %s", m) // Prepare response response = nil logger.SetPrefix("* .. ") switch req["command"] { case ADDVERTEX: // Generate id id := "v_" + randId() // Add element to array elements = append(elements, id) // Return element ID response = &Response{ Requestid: req["requestId"].(string), Success: true, Body: map[string]string{"id": id}, } case CHANGEVERTEX: // In the case of changing element name, check if // it starts with `v_`. props := req["properties"].(map[string]interface{}) if props["name"] == nil || strings.HasPrefix(props["name"].(string), "v_") { response = &Response{ Requestid: req["requestId"].(string), Success: true, } } else { response = &Response{ Requestid: req["requestId"].(string), Success: false, Body: map[string]string{"error": "Bad name!"}, } } case ADDEDGE: // Generate id id := "e_" + randId() // Add element to array elements = append(elements, id) // Return element ID response = &Response{ Requestid: req["requestId"].(string), Success: true, Body: map[string]string{"id": id}, } case CHANGEEDGE: // In the case of changing element name, check if // it starts with `v_`. props := req["properties"].(map[string]interface{}) if props["name"] == nil || strings.HasPrefix(props["name"].(string), "e_") { response = &Response{ Requestid: req["requestId"].(string), Success: true, } } else { response = &Response{ Requestid: req["requestId"].(string), Success: false, Body: map[string]string{"error": "Bad name!"}, } } case NEXT: if counter == len(elements)*3 || counter == -1 { response = &Response{ Requestid: req["requestId"].(string), Success: true, Body: map[string]string{"message": "Finished running"}, } } else { element := elements[rand.Intn(len(elements))] var elementType string switch element[0:1] { case "v": elementType = "vertex" case "e": elementType = "edge" } response = &Response{ Requestid: req["requestId"].(string), Success: true, // Return just a random element Body: map[string]string{ "next": element, "type": elementType, }, } counter++ } case START: if len(elements) == 0 { response = &Response{ Requestid: req["requestId"].(string), Success: false, Body: map[string]string{"error": "Model is empty"}, } } else { counter = 0 response = &Response{ Requestid: req["requestId"].(string), Success: true, } } case STOP: counter = -1 response = &Response{ Requestid: req["requestId"].(string), Success: true, } default: logger.Print("Unknown command %s", req["command"]) } if response != nil { m, _ := json.Marshal(response) time.Sleep(DELAY * time.Millisecond) logger.Print("Sent response: %s", m) websocket.JSON.Send(ws, response) response = nil } } logger.Print("Closed connection from %s", ws.LocalAddr().String()) }
// Echo the data received on the WebSocket. func EchoServer(ws *websocket.Conn) { totle++ fmt.Println(totle, ws.LocalAddr()) io.Copy(ws, ws) }