Example #1
0
func handleWebsocket(s *websocket.Conn) {
	var data [8192]uint8
	log.Printf("Opened WebSocket")
	startTime := time.Now()

	f, err := os.OpenFile(fmt.Sprintf("%s/uploads/%s.mp3", *htdocsDir, time.Now().Format(time.RFC3339)), os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("os.OpenFile failed: %v", err)
		return
	}
	defer f.Close()

	sum := 0
	count := 0

	for {
		n, err := s.Read(data[:])
		if err != nil {
			log.Printf("s.Read failed: %v", err)
			break
		}
		log.Printf("Received WebSocket frame: %d bytes", n)
		count++
		sum += n
		if _, err := f.Write(data[:n]); err != nil {
			log.Printf("f.Write failed: %v", err)
		}
	}

	duration := time.Since(startTime)

	log.Printf("Closed WebSocket, received %d frames (%d bytes), took %s (%.3f kb/s)", count, sum, duration, (float64(sum)/duration.Seconds())/float64(1024))
}
Example #2
0
func wsockHandler(ws *websocket.Conn) {
	// Start a sniffer.
	req := ws.Request()
	req.ParseForm()
	local := req.Form.Get("local")
	remote := req.Form.Get("remote")

	if local != "" && remote != "" {
		l, err := net.Listen("tcp", local)
		if err != nil {
			sendMessage(ws, "error", err.Error())
			ws.Close()
			return
		}

		go func() {
			buf := make([]byte, 256)
			for {
				_, err := ws.Read(buf)
				if err != nil {
					l.Close()
					return
				}
			}
		}()

		fn := func(m map[string]interface{}) error {
			return websocket.JSON.Send(ws, m)
		}
		fromClient := webSniffer{fn, true}
		fromServer := webSniffer{fn, false}
		err = sniffer.SniffToOutput(l, remote, fromClient, fromServer)
		ws.Close()
	}
}
Example #3
0
func initSocket(ws *websocket.Conn) {
	sendq := make(chan []byte, 100)
	recvq := make(chan []byte, 5)

	width, height := getResolution(ws)
	fmt.Printf("User requested size %d x %d\n", width, height)

	settings := &rdpConnectionSettings{
		hostname,
		username,
		password,
		int(width),
		int(height),
	}

	go rdpconnect(sendq, recvq, settings)
	go processSendQ(ws, sendq)

	read := make([]byte, 1024, 1024)
	for {
		_, err := ws.Read(read)
		if err != nil {
			recvq <- []byte("1")
		}
	}
}
Example #4
0
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)
		}
	}
}
Example #5
0
func readMsg(conn *websocket.Conn, owner string) {
	tmp := make([]byte, 32)
	buf := make([]byte, 0)
	for {
		readlen, err := conn.Read(tmp)
		if err != nil {
			break
		}

		buf = append(buf, tmp[0:readlen]...)
		lensep := strings.Index(string(buf), ":")
		if lensep < 0 {
			continue
		}

		msglen, err := strconv.Atoi(string(buf[0:lensep]))
		if err != nil {
			log.Println("error: ", err)
			break
		}

		if len(buf) < msglen+lensep+1 {
			continue
		}

		msg := Msg{owner, make([]byte, msglen)}
		copy(msg.data, buf[lensep+1:msglen+lensep+1])
		read <- msg
		buf = buf[lensep+msglen+1:]
	}
}
Example #6
0
func (endpoint *WebsocketEndpoint) Handle(ws *websocket.Conn) {
	ws.PayloadType = websocket.BinaryFrame

	var buf = make([]byte, 1024*64)

	var sessConn = &WebsocketSessionConnection{
		conn: ws,
	}
	var session Session = endpoint.context.CreateSession(sessConn)

	fmt.Printf("New session: %s\n", session.ID())

	for {

		msgLength, err := ws.Read(buf)

		if err != nil {
			if err != io.EOF {
				fmt.Printf("WS error: %#v\n", err)
			}
			fmt.Printf("Session closed: %s\n", session.ID())
			break
		}

		if msgLength == 0 {
			continue
		}

		var msgBuf = make([]byte, msgLength)
		copy(msgBuf, buf)

		endpoint.Handler(endpoint, msgBuf, session, ws)
	}
}
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()
}
Example #8
0
func read(t *testing.T, conn *websocket.Conn) string {
	var data = make([]byte, 512)
	n, err := conn.Read(data)
	if err != nil {
		t.Errorf("conn.Read(%v) got error: %v, want nil", data, err)
	}
	return string(data[0:n])
}
Example #9
0
// 从WebSocket客户端接收信号
func WaitSignal(ws *websocket.Conn, notify_stop_chan chan<- bool, timer **time.Timer,
	pause *bool, resume_chan chan bool, elapsed *int64, mutex *sync.Mutex) {

	var start_time int64
	var end_time int64

	for {
		// 设置Read Deadline为24小时
		ws.SetReadDeadline(time.Now().Add(86400 * time.Second))

		buf := make([]byte, 8)
		_, err := ws.Read(buf)

		if err != nil {
			log.Println("Playback Server: Read data from client failed: ", err)
			mutex.Lock()
			if (*timer) != nil {
				(*timer).Reset(time.Duration(time.Nanosecond))
			}
			mutex.Unlock()
			notify_stop_chan <- true
			goto end
		}

		data, _ := strconv.Atoi(string(recorder.GetValidByte(buf)))
		if data == 800 { // 关闭
			// 如果执行了暂停,首先取消暂停
			if *pause == true {
				resume_chan <- true
			}
			// 取消定时器,发送结束信号
			mutex.Lock()
			if (*timer) != nil {
				(*timer).Reset(time.Duration(time.Nanosecond))
			}
			mutex.Unlock()
			notify_stop_chan <- true
			goto end
		} else if data == 801 { // 暂停
			if *pause == false {
				// 设置暂停标志,记录暂停开始时间
				*pause = true
				start_time = getNowMillisecond()
			}
		} else if data == 802 { // 恢复
			if *pause == true {
				// 记录暂停结束时间,向恢复的channel发送信号
				end_time = getNowMillisecond()
				*elapsed += (end_time - start_time)
				*pause = false
				resume_chan <- true
			}
		}
	}

end:
	ws.Close()
}
Example #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()
}
func readFromServer(ws *websocket.Conn) {
	buf := make([]byte, 1000)
	for {
		if _, err := ws.Read(buf); err != nil {
			fmt.Printf("%s\n", err.Error())
			break
		}
	}
}
Example #12
0
func socketServer(ws *websocket.Conn) {
	defer ws.Close()
	buffer := make([]byte, BUFFER_SIZE)
	n, err := ws.Read(buffer)
	var hello HelloMessage
	err = json.Unmarshal(buffer[:n], &hello)
	if err != nil {
		fmt.Println("Could not parse welcome message.")
		return
	}
	fmt.Println("Client", hello.UUID, "connected")

	client := NewClient(hello.UUID)

	closeSocket := func() {
		client, ok := clients[hello.UUID]
		if ok {
			fmt.Println("Client disconnected", hello.UUID)
			client.close()
			delete(clients, hello.UUID)
		} // else was already closed before
	}

	defer closeSocket()

	// Read frame from socket and forward it to request channel
	go func() {
		defer quietPanicRecover()
		for {
			requestId, buffer, err := ReadFrame(ws)
			if err != nil {
				//fmt.Println("Read error", err)
				closeSocket()
				return
			}
			req := client.pendingRequests[requestId]
			if req == nil {
				fmt.Println("Got response for non-existent request", requestId, string(buffer))
				continue
			}
			req.ch <- buffer
		}
	}()

	for {
		writeBuffer, request_ok := <-client.writeChannel
		if !request_ok {
			return
		}
		err = WriteFrame(ws, writeBuffer[0], writeBuffer[1:])
		if err != nil {
			fmt.Println("Got error", err)
			return
		}
	}
}
Example #13
0
func wshandler(ws *websocket.Conn) {
	config.clients.Lock()
	config.clients.conns = append(config.clients.conns, ws)
	config.clients.Unlock()

	// Wait until the client disconnects.
	// We're not expecting the client to send real data to us
	// so websocket.Read() can be used as a convenient way to block
	ws.Read(nil)
}
Example #14
0
// WsReader reads from a web socket and return pass the string to a channel
func WsReader(conn *websocket.Conn, c chan string) {
	var n int
	msg := make([]byte, 512)
	n, err := conn.Read(msg)
	if err != nil {
		panic(err)
	}
	c <- fmt.Sprintf("Receive : %s", msg[:n])
	return
}
Example #15
0
// 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])
	}
}
Example #16
0
func (mch *messageCountingHandler) handle(conn *websocket.Conn) {
	buffer := make([]byte, 1024)
	var err error
	for err == nil {
		_, err = conn.Read(buffer)
		if err == nil {
			atomic.AddInt32(&mch.msgCount, 1)
		}
	}
}
Example #17
0
// 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])
	}
}
func server(ws *websocket.Conn) {
	fmt.Printf("new connection\n")
	buf := make([]byte, 100)
	for {
		if _, err := ws.Read(buf); err != nil {
			fmt.Printf("%s", err.Error())
			break
		}
	}
	fmt.Printf(" => closing connection\n")
	ws.Close()
}
Example #19
0
File: ws.go Project: Joinhack/peony
//@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])
		}
	}
}
// 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)
}
Example #21
0
File: main.go Project: kr/wsdemo
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
		}
	}
}
Example #22
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])
}
Example #23
0
// Entrance method for new websocket connections
func clientConnection(clientsock *websocket.Conn) {
	packet := pnet.NewPacket()
	buffer := make([]uint8, pnet.PACKET_MAXSIZE)
	recv, err := clientsock.Read(buffer)
	if err == nil {
		copy(packet.Buffer[0:recv], buffer[0:recv])
		packet.GetHeader()
		parseFirstMessage(clientsock, packet)
	} else {
		if err.Error() != "EOF" {
			log.Warning("GameServer", "clientConnection", "Client connection error: %v", err.Error())
		}
	}
}
Example #24
0
// Echo the data received on the WebSocket.
func echoServer(ws *websocket.Conn) {
	clientShadow := shadow{shadowstring: "shadow"}
	clientBackup := backup{backupstring: "backup"}
	for {
		buffer := make([]byte, 512)
		readData, _ := ws.Read(buffer)
		str := string(buffer[:readData])

		if str != "" {
			differances(str, &clientBackup, &clientShadow)

			readfile("fileServer.txt")
		}
	}
}
Example #25
0
// Helper function to read a complete message from a WebSocket (because the API makes it hard)
func readWebSocketMessage(conn *websocket.Conn) ([]byte, error) {
	var message []byte
	buf := make([]byte, 100)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			return nil, err
		}
		message = append(message, buf[0:n]...)
		if n < len(buf) {
			break
		}
	}
	return message, nil
}
Example #26
0
func readWriteServer(ws *websocket.Conn) {
	buf := make([]byte, 100)
	for {
		fmt.Printf("%v\n", ws)
		fmt.Printf("Path: %#v\n", ws)
		fmt.Println("wrong")
		//os.Exit(1)

		// Read, max 100 byte chunks at a time
		n, err := ws.Read(buf)
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Printf("recv:%q\n", buf[:n])
	}

	switch string(buf) {
	case "foo":
		//		cmd := exec.Command("/usr/bin/gdb", *file)

		// Get stdin pipe for controls
		//		cmd.Stdin = strings.NewReader("")
		//		inPipe, err := cmd.StdinPipe()
		//		if err != nil {
		//			log.Fatal(err)
		//		}

		// Output collector
		//		out, err := cmd.Output()
		//		if err != nil {
		//			log.Fatal(err)
		//		}

		//_ = inPipe
		//		rep := []byte{'\n', '<', 'b', 'r', '>'}
		//		newline := []byte{'\n'}

		//		n, err = ws.Write(bytes.Replace(out, newline, rep, -1))
		//		if err != nil {
		//			fmt.Println(err)
		//			break
		//		}
	}
	fmt.Println("readWriteServer finished")
}
Example #27
0
func listen(ws *websocket.Conn) {
	// NOTE: Could use websocket.JSON.Receive
	var buf = make([]byte, 512)
	for {
		n, err := ws.Read(buf)
		if err != nil {
			println(err.Error())
			ws.Close()
			return
		}
		if string(buf[:n]) == "ok" {
			tick <- struct{}{}
			continue
		}
		forwardEvent(buf[:n])
	}
}
Example #28
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()
}
Example #29
0
func publisher(ch_trigger chan int, ch_time chan time.Time, 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(50 * time.Millisecond)
			continue
		}
		break
	}

	var msg = make([]byte, 512)

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

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

	for {
		<-ch_trigger

		if _, err := ws.Write([]byte(publish_message)); err != nil {
			fmt.Println("publisher publish write error")
			log.Fatal(err)
		}

		ch_time <- time.Now()

		if _, err = ws.Read(msg); err != nil {
			fmt.Println("publisher publish read error")
			log.Fatal(err)
		}

		if _, err = ws.Read(msg); err != nil {
			fmt.Println("publisher message read error")
			log.Fatal(err)
		}

	}
}
Example #30
0
func detectWebSocketClose(ws *websocket.Conn, ch chan bool) {
	var msg [1024]byte
	for {
		n, err := ws.Read(msg[:])
		if err != nil {
			if err == io.EOF {
				log.Println("Reached to WebSocket EOF")
			} else {
				log.Println("WebSocket read error:", err)
			}
			break
		}
		if n == 0 {
			break
		}
	}
	close(ch)
}