func docServer(ws *websocket.Conn) {
	for {
		in := make([]byte, 512)
		n, err := ws.Read(in)
		if err != nil {
			fmt.Println(err)
			break
		}

		fmt.Println(string(in[:n]))

		msg := &Message{}
		json.Unmarshal(in[:n], &msg)
		switch msg.DocType {
		case "req":
			response := &DocumentMessage{DocType: "doc", Version: doc.Version, Content: doc.Content}
			json, _ := json.Marshal(response)
			ws.Write(json)
		case "edit":
			editMsg := &EditMessage{}
			json.Unmarshal(in[:n], &editMsg)
			doc.RemoteVersion = editMsg.Edits[len(editMsg.Edits)-1].Version
			response := &AckMessage{DocType: "ack", Version: doc.RemoteVersion}
			json, _ := json.Marshal(response)
			ws.Write(json)
		}
	}
}
Exemple #2
0
func (endpoint *WebsocketEndpoint) HandleAPI(
	buf []byte, session Session, ws *websocket.Conn) {

	var data APIData
	var resolver = msgpack.DefaultDecoderContainerResolver
	resolver.MapType = reflect.TypeOf(make(APIData))

	var dec = msgpack.NewDecoder(bytes.NewReader(buf), &resolver)

	var err = dec.Decode(&data)

	if err != nil {
		fmt.Printf("Decode err: %v\n", err)
		return
	}

	var response = endpoint.context.API().HandleRequest(
		data, session, endpoint.context)

	if id, ok := data["id"]; ok {
		response["id"] = id
	}

	w := bytes.NewBufferString("")
	w.WriteByte('a')
	enc := msgpack.NewEncoder(w)
	err = enc.Encode(response)

	if err != nil {
		fmt.Printf("Encode err: %#v\n", err)
		return
	}

	ws.Write(w.Bytes())
}
func (fh *FakeHandler) handle(conn *websocket.Conn) {
	fh.call()
	request := conn.Request()
	fh.setLastURL(request.URL.String())
	fh.setAuthHeader(request.Header.Get("Authorization"))

	if fh.messageReceived != nil {
		go func() {
			for {
				buffer := make([]byte, 1024)
				_, err := conn.Read(buffer)

				if err == nil {
					fh.messageReceived <- true
				} else {
					break
				}
			}
		}()
	}

	for _, protoMessage := range fh.Messages {
		if protoMessage == nil {
			conn.Write([]byte{})
		} else {
			message, err := proto.Marshal(protoMessage)
			Expect(err).ToNot(HaveOccurred())

			conn.Write(message)
		}
	}

	<-fh.closeConnection
	conn.Close()
}
Exemple #4
0
// Write received messages from a channel to the websocket client
func FrameServer(conn *websocket.Conn) {
	// Set the PayloadType to binary
	conn.PayloadType = websocket.BinaryFrame

	client := NewClient()

	registerClient <- client
	defer func() {
		unregisterClient <- client
	}()

	// Write the header as the first message to the client (MPEG size etc.)
	conn.SetWriteDeadline(time.Now().Add(ClientWriteTimeout * time.Second))
	if _, err := conn.Write(*headerMessage); err != nil {
		return
	}

	// Continuously read messages from the queue and write to the client, stop on error
	for msg := range client.queue {
		conn.SetWriteDeadline(time.Now().Add(ClientWriteTimeout * time.Second))
		if _, err := conn.Write(*msg); err != nil {
			return
		}
	}
}
func syscallHandler(conn *websocket.Conn) {
	reader := bufio.NewReader(conn)
	decoder := json.NewDecoder(reader)

	for {
		var command map[string]interface{}

		if err := decoder.Decode(&command); err == io.EOF {
			break
		} else if err != nil {
			log.Println("Decoder error", err)
			continue
		}

		if response, err := handleSyscall(conn, command); err != nil {
			log.Println(err)
			continue
		} else {
			if _, err := conn.Write(response); err != nil {
				log.Println(err)
				continue
			}
		}
	}
}
Exemple #6
0
func redirToWs(fd int, ws *websocket.Conn) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "Error occured: %s\n", r)
			runtime.Goexit()
		}
	}()

	var buf [8192]byte
	start, end, buflen := 0, 0, 0
	for {
		switch nr, er := syscall.Read(fd, buf[start:]); {
		case nr < 0:
			fmt.Fprintf(os.Stderr, "error reading from websocket %d with code %d\n", fd, er)
			return
		case nr == 0: // EOF
			return
		case nr > 0:
			buflen = start + nr
			for end = buflen - 1; end >= 0; end-- {
				if utf8.RuneStart(buf[end]) {
					ch, width := utf8.DecodeRune(buf[end:buflen])
					if ch != utf8.RuneError {
						end += width
					}
					break
				}

				if buflen-end >= 6 {
					fmt.Fprintf(os.Stderr, "Invalid UTF-8 sequence in output")
					end = nr
					break
				}
			}

			runes := bytes.Runes(buf[0:end])
			buf_clean := []byte(string(runes))

			nw, ew := ws.Write(buf_clean[:])
			if ew != nil {
				fmt.Fprintf(os.Stderr, "error writing to websocket with code %s\n", ew)
				return
			}

			if nw != len(buf_clean) {
				fmt.Fprintf(os.Stderr, "Written %d instead of expected %d\n", nw, end)
			}

			start = buflen - end

			if start > 0 {
				// copy remaning read bytes from the end to the beginning of a buffer
				// so that we will get normal bytes
				for i := 0; i < start; i++ {
					buf[i] = buf[end+i]
				}
			}
		}
	}
}
// Creates and returns a new Connection object
// Finds token within request URI
func NewConnection(ws *websocket.Conn) (*Connection, error) {

	if origin := ws.RemoteAddr(); origin.String() != "http://lab.quantumtrip.org" && origin.String() != "localhost" {
		log.Println("Unkown origin: \n\tTo: %s\n\tFrom: %s", origin, ws.Request().RemoteAddr)
		//os.Exit(68)
		msg := "Please email [email protected] for access"
		b, err := json.Marshal(msg)
		if err != nil {
			log.Panic(err)
		}

		ws.Write(b)
	}

	query := ws.Request().URL.Query()
	token := GetToken(query)

	user, err := getUser(token)
	if err != nil {
		log.Println(err.Error())
		ws.Close()
		return nil, err
	}

	client := ClientInfo{token, ws.Request().RemoteAddr, user}
	log.Printf("Connection opened %+v", client)

	return &Connection{
		make(chan bool),
		make(chan interface{}),
		client,
		ws,
	}, nil
}
Exemple #8
0
func SendDeviceStatusMessage(ws *websocket.Conn, status DeviceStatus) error {
	msg, err := json.Marshal(DeviceStatusMessage{status})
	if err != nil {
		panic("json.Marshal")
	}
	_, err = ws.Write(msg)
	return err
}
Exemple #9
0
func sendPowerPointExtraReturnInfo(request []byte, extraReturnInfo string, ws *websocket.Conn) {
	switch request[1] {
	case 'p', 'n', 'r', 'l':
		// 傳回目前投影片的備忘稿; 縮圖的網址也直接傳回去,讓瀏覽器判斷
		ws.Write([]byte(extraReturnInfo))
	}

}
Exemple #10
0
func goRun(ws *websocket.Conn, file string) {
	var ospath string
	gopaths := filepath.SplitList(build.Default.GOPATH)

	for _, gopath := range gopaths {
		p := filepath.Join(gopath, "src", file)
		_, err := os.Stat(p)
		if err == nil {
			ospath = p
			break
		}
	}

	// File was not found
	if ospath == "" {
		return
	}

	c := exec.Command("go", "run", ospath)
	out, in, err := start(c)
	if err != nil {
		panic(err)
	}

	go func() {
		for {
			buf := make([]byte, 1024, 1024)
			n, err := out.Read(buf)
			if err != nil {
				break
			}

			n, err = ws.Write(buf[:n])
			if err != nil {
				break
			}
		}

		ws.Close()
	}()

	buf := make([]byte, 1024, 1024)
	for {
		n, err := ws.Read(buf)
		if err != nil {
			break
		}

		n, err = in.Write(buf[:n])
		if err != nil {
			break
		}
	}

	out.Close()
	in.Close()
	c.Wait()
}
Exemple #11
0
func writer(ws *websocket.Conn, responses chan []byte) {
	defer ws.Close()
	for bytes := range responses {
		if _, err := ws.Write(bytes); err != nil {
			println("Writer Error", err.Error())
			return
		}
	}
}
// Echo the data received on the WebSocket.
func echoServer(ws *websocket.Conn) {
	//io.Copy(ws, ws)
	for {
		buffer := make([]byte, 512)
		readData, _ := ws.Read(buffer)
		str := string(buffer[:readData])
		fmt.Println(str)
		ws.Write(buffer[:readData])
	}
}
// Echo the data received on the WebSocket.
func echoServer(ws *websocket.Conn) {
	//io.Copy(ws, ws)
	for {
		in := make([]byte, 512)
		n, _ := ws.Read(in)
		s := string(in[:n])
		fmt.Println(s)
		ws.Write(in[:n])
	}
}
Exemple #14
0
// Writes the contents of sMsg back to ws, returning any errors encountered
func writeback(ws *websocket.Conn, sMsg *msgdef.ServerMsg) error {
	msg := sMsg.Msg
	bytes, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	logutil.Log(sMsg.TId, sMsg.UId, fmt.Sprintf("Server Sent: %s", bytes))
	_, err = ws.Write(bytes)
	return err
}
Exemple #15
0
func RunClient(url string, id string, userKey string) {
	rootPath, _ = filepath.Abs(rootPath)
	ListenForSignals()
	socketUrl := fmt.Sprintf("%s/clientsocket", url)
	var ws *websocket.Conn
	var timeout time.Duration = 1e8
	config, err := websocket.NewConfig(socketUrl, socketUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	config.TlsConfig = new(tls.Config)
	// Disable this when getting a proper certificate
	config.TlsConfig.InsecureSkipVerify = true
	for {
		time.Sleep(timeout)
		var err error
		ws, err = websocket.DialConfig(config)
		timeout *= 2
		if err != nil {
			fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
		} else {
			break
		}
	}

	buffer, _ := json.Marshal(HelloMessage{"0.1", id, userKey})

	if _, err := ws.Write(buffer); err != nil {
		log.Fatal(err)
		return
	}
	connectUrl := strings.Replace(url, "ws://", "http://", 1)
	connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
	multiplexer := NewRPCMultiplexer(ws, handleRequest)

	if userKey == "" {
		fmt.Print("In the Zed application copy and paste following URL to edit:\n\n")
		fmt.Printf("  %s/fs/%s\n\n", connectUrl, id)
	} else {
		fmt.Println("A Zed window should now open. If not, make sure Zed is running and configured with the correct userKey.")
	}
	fmt.Println("Press Ctrl-c to quit.")
	err = multiplexer.Multiplex()
	if err != nil {
		// TODO do this in a cleaner way (reconnect, that is)
		if err.Error() == "no-client" {
			fmt.Printf("ERROR: Your Zed editor is not currently connected to zedrem server %s.\nBe sure Zed is running and the project picker is open.\n", url)
		} else {
			RunClient(url, id, userKey)
		}
	}
}
Exemple #16
0
func wsMemoryConsoHandler(ws *websocket.Conn) {
	for {
		memory := new(linuxproc.Memory)
		mf, _ := memory.MemFree()
		mt, _ := memory.MemTotal()
		// utiliser json.MArshal car là, c'est moche ...
		msg := fmt.Sprintf("[{\"name\":\"free\",\"y\":%.2f,\"color\":\"#D0FA58\"},{\"name\":\"occ\",\"y\":%.2f,\"color\":\"#F78181\"}]", float32(mf)*9.53674316406E-7, float32(mt)*9.53674316406E-7-float32(mf)*9.53674316406E-7)
		name := []byte(msg)
		ws.Write(name)
		time.Sleep(250 * time.Millisecond)
	}
}
Exemple #17
0
//@Mapper("/echo", method="WS")
func (c *WebSocket) Echo(ws *websocket.Conn) {
	var bs [1024]byte
	for {
		if n, err := ws.Read(bs[:]); err != nil {
			peony.ERROR.Println(err)
			return
		} else {
			peony.INFO.Println("recv info:", string(bs[:n]))
			ws.Write(bs[:n])
		}
	}
}
Exemple #18
0
// Twitter検索
func twitterSearchHandler(ws *websocket.Conn) {
	defer ws.Close()

	// 検索キーワードの取得
	req := ws.Request() // http.Requestが返る
	query := req.FormValue("q")
	log.Printf("query: %s", query)

	// Twitter streaming APIに接続
	client := twitterstream.NewClientTimeout(
		*consumerKey,
		*consumerSecret,
		*accessToken,
		*accessTokenSecret,
		timeout,
	)
	conn, err := client.Track(query)
	if err != nil {
		log.Printf("Tracking failed: %s", err)
		return
	}
	defer conn.Close()

	for {
		if tweet, err := conn.Next(); err == nil {
			// Tweetが公式Retweetだった場合はなにもしない
			if tweet.RetweetedStatus != nil {
				continue
			}

			// Websocketに流すJSONを作成
			data := WSTweet{
				tweet.Text,
				tweet.User.Name,
				tweet.User.ScreenName,
				tweet.User.ProfileImageUrl,
			}
			json, _ := json.Marshal(data)

			// Websocketに流す
			_, err = ws.Write(json)
			if err != nil {
				log.Printf("Writing to Websocket failed: %s", err)
				return
			}
		} else {
			log.Printf("Decoding tweet failed: %s", err)
			return
		}
	}
}
Exemple #19
0
func echoHandler(ws *websocket.Conn) {
	msg := make([]byte, 512)
	n, err := ws.Read(msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Receive: %s\n", msg[:n])

	m, err := ws.Write(msg[:n])
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Send: %s\n", msg[:m])
}
Exemple #20
0
func debugSocket(ws *websocket.Conn) {
	_, pidStr := path.Split(ws.Request().URL.Path)
	pid, err := strconv.ParseInt(pidStr, 10, 64)

	if err != nil {
		ws.Write([]byte("Process not found or is finished"))
		ws.Close()
		return
	}

	response := make(chan *ProcessData)
	GetProcessData <- &ProcessDataRequest{int(pid), response}
	procData := <-response

	if procData == nil {
		ws.Write([]byte("Process not found or is finished"))
		ws.Close()
		return
	}

	for {
		buffer := <-procData.output

		if buffer == "" {
			ws.Write([]byte(""))
			ws.Close()
			break
		}

		ws.Write([]byte(buffer))
	}
}
Exemple #21
0
func Echo(ws *websocket.Conn) {
	defer ws.Close()
	buf := make([]byte, 64*1024)
	for {
		n, err := ws.Read(buf)
		if err != nil {
			return
		}
		_, err = ws.Write(buf[:n])
		if err != nil {
			return
		}
	}
}
// Echo the data received on the Web Socket.
func EchoServer(ws *websocket.Conn) {
	// io.Copy(ws, ws);
	var msg = make([]byte, 512)
	n, err := ws.Read(msg)
	if err != nil {
		log.Fatalf("Read: %v", err)
	}
	reply := fmt.Sprintf("You said: '%s'", msg[:n])
	_, err = ws.Write([]byte(reply))
	if err != nil {
		log.Fatalf("Write: %v", err)
	}
	fmt.Printf("Replied to user with...\n%s\n", reply)
}
Exemple #23
0
//Оповещает клиента об ошибке
func sendError(ws *websocket.Conn, error string) {
	//Создаем пакет, у которого заполнено только поле ошибки
	packet := packet{Error: error}
	//Кодируем его в json
	msg, _, err := websocket.JSON.Marshal(packet)
	if err != nil {
		fmt.Println(err)
		return
	}

	//И отправляем клиенту
	if _, err := ws.Write(msg); err != nil {
		fmt.Println(err)
	}
}
Exemple #24
0
func receiverHandler(ws *websocket.Conn) {
	messages := make([][]byte, 0)
	msgCount := len(Outgoing)
	if msgCount == 0 {
		return
	}
	for i := 0; i < msgCount; i++ {
		messages = append(messages, <-Outgoing)
	}

	wire, err := json.Marshal(messages)
	if err != nil {
		ws.Close()
	}
	ws.Write(wire)
}
Exemple #25
0
func wsMemoryProcessHandler(ws *websocket.Conn) {
	i := 0
	for {
		lp := listProcess()
		lpoints := []string{}
		for _, p := range lp {
			// t := time.Now().Unix()
			// utiliser json.MArshal car là, c'est moche ...
			lpoints = append(lpoints, fmt.Sprintf("{\"peak\":%.2f,\"data\":%.2f,\"name\":\"%s\",\"pid\":%d,\"state\":\"%s\"}", float32(p.VmData)*9.53674316406E-7, float32(p.VmPeak)*9.53674316406E-7, p.Name, p.Pid, p.State))
		}
		msg, _ := json.Marshal(lpoints)
		ws.Write(msg)
		time.Sleep(2000 * time.Millisecond)
		i += 1
	}
}
Exemple #26
0
func send(ws *websocket.Conn, path string, evs <-chan store.Event) {
	l := len(path) - 1
	for ev := range evs {
		ev.Getter = nil // don't marshal the entire snapshot
		ev.Path = ev.Path[l:]
		b, err := json.Marshal(ev)
		if err != nil {
			log.Println(err)
			return
		}
		_, err = ws.Write(b)
		if err != nil {
			log.Println(err)
			return
		}
	}
}
Exemple #27
0
func EchoServer(ws *websocket.Conn) {
	counter += 1
	defer func() {
		counter -= 1
	}()
	for {
		var msg = make([]byte, 512)
		if _, err := ws.Read(msg); err != nil {
			break
		}

		if _, err := ws.Write(msg); err != nil {
			break
		}
	}
	ws.Close()
}
Exemple #28
0
func RunClient(url string, id string) {
	rootPath, _ = filepath.Abs(rootPath)

	socketUrl := fmt.Sprintf("%s/clientsocket", url)
	var ws *websocket.Conn
	var timeout time.Duration = 1e8
	config, err := websocket.NewConfig(socketUrl, socketUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	config.TlsConfig = new(tls.Config)
	// Disable this when getting a proper certificate
	config.TlsConfig.InsecureSkipVerify = true
	for {
		time.Sleep(timeout)
		var err error
		ws, err = websocket.DialConfig(config)
		timeout *= 2
		if err != nil {
			fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
		} else {
			break
		}
	}

	buffer, _ := json.Marshal(HelloMessage{"0.1", id})

	if _, err := ws.Write(buffer); err != nil {
		log.Fatal(err)
		return
	}
	connectUrl := strings.Replace(url, "ws://", "http://", 1)
	connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
	multiplexer := NewRPCMultiplexer(ws, handleRequest)

	fmt.Print("In the Zed Chrome application copy and paste following URL to edit:\n\n")
	fmt.Printf("  %s/fs/%s\n\n", connectUrl, id)
	fmt.Println("Press Ctrl-c to quit.")
	err = multiplexer.Multiplex()
	if err != nil {
		// TODO do this in a cleaner way (reconnect, that is)
		RunClient(url, id)
	}
}
Exemple #29
0
func subscriber(ch_sub, ch_msg, ch_start chan int, url, origin, connect_message, subscribe_message, publish_message string) {
	var err error
	var ws *websocket.Conn
	for {
		ws, err = websocket.Dial(url, "", origin)
		if err != nil {
			//fmt.Println("Connection fails, is being re-connection")
			time.Sleep(10 * time.Millisecond)
			continue
		}
		break
	}
	if _, err := ws.Write([]byte(connect_message)); err != nil {
		fmt.Println("subscriber connect write error")
		log.Fatal(err)
	}
	var msg = make([]byte, 512)

	if _, err = ws.Read(msg); err != nil {
		fmt.Println("subscriber connect read error")
		log.Fatal(err)
	}
	//fmt.Printf("Received: %s.\n", msg[:n])

	if _, err := ws.Write([]byte(subscribe_message)); err != nil {
		fmt.Println("subscriber subscribe write error")
		log.Fatal(err)
	}
	if _, err = ws.Read(msg); err != nil {
		fmt.Println("subscriber subscribe read error")
		log.Fatal(err)
	}

	ch_sub <- 1

	for {
		if _, err = ws.Read(msg); err != nil {
			fmt.Println("subscriber msg read error")
			log.Fatal(err)
		}
		//fmt.Println("message received")
		ch_msg <- 1
	}

}
Exemple #30
0
func responseWriter(ws *websocket.Conn, ret int, result map[string]interface{}) error {
	result["ret"] = ret
	result["msg"] = getErrMsg(ret)
	strJson, err := json.Marshal(result)
	if err != nil {
		Log.Printf("json.Marshal(\"%v\") failed", result)
		return err
	}

	respJson := string(strJson)
	Log.Printf("Respjson : %s", respJson)
	if _, err := ws.Write(strJson); err != nil {
		Log.Printf("ws.Write(\"%s\") failed (%s)", respJson, err.Error())
		return err
	}

	return nil
}