當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Conn.Read方法代碼示例

本文整理匯總了Golang中code/google/com/p/go/net/websocket.Conn.Read方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.Read方法的具體用法?Golang Conn.Read怎麽用?Golang Conn.Read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在code/google/com/p/go/net/websocket.Conn的用法示例。


在下文中一共展示了Conn.Read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: handleWebsocket

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))
}
開發者ID:balazsbela,項目名稱:speech-to-server,代碼行數:33,代碼來源:main.go

示例2: wsockHandler

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()
	}
}
開發者ID:mrlauer,項目名稱:sniffer,代碼行數:35,代碼來源:websniffer.go

示例3: initSocket

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")
		}
	}
}
開發者ID:pauljz,項目名稱:go-freerdp-webconnect,代碼行數:26,代碼來源:main.go

示例4: docServer

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)
		}
	}
}
開發者ID:rgson,項目名稱:ds-codesync-prototype,代碼行數:28,代碼來源:ds-stub.go

示例5: readMsg

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:]
	}
}
開發者ID:carter2000,項目名稱:chat,代碼行數:31,代碼來源:httpserver.go

示例6: Handle

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)
	}
}
開發者ID:brendonh,項目名稱:go-service,代碼行數:34,代碼來源:websocket.go

示例7: handle

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()
}
開發者ID:khwang1,項目名稱:loggregator_consumer,代碼行數:35,代碼來源:consumer_test.go

示例8: read

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])
}
開發者ID:xaccc,項目名稱:apprtc-server,代碼行數:8,代碼來源:collider_test.go

示例9: WaitSignal

// 從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()
}
開發者ID:sdgdsffdsfff,項目名稱:wisemonitor,代碼行數:59,代碼來源:server.go

示例10: goRun

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()
}
開發者ID:XQYCHJ,項目名稱:godev,代碼行數:58,代碼來源:debug.go

示例11: readFromServer

func readFromServer(ws *websocket.Conn) {
	buf := make([]byte, 1000)
	for {
		if _, err := ws.Read(buf); err != nil {
			fmt.Printf("%s\n", err.Error())
			break
		}
	}
}
開發者ID:romelgomez,項目名稱:notas-sobre-golang,代碼行數:9,代碼來源:websocket_client.go

示例12: socketServer

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
		}
	}
}
開發者ID:naerbnic,項目名稱:zed,代碼行數:56,代碼來源:server.go

示例13: wshandler

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)
}
開發者ID:porjo,項目名稱:gowebwatcher,代碼行數:10,代碼來源:gowebwatcher.go

示例14: WsReader

// 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
}
開發者ID:yml,項目名稱:wsbench,代碼行數:11,代碼來源:wsbench.go

示例15: echoServer

// 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])
	}
}
開發者ID:rgson,項目名稱:ds-codesync-prototype,代碼行數:11,代碼來源:wsserver.go


注:本文中的code/google/com/p/go/net/websocket.Conn.Read方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。