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


Golang Conn.Read方法代碼示例

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


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

示例1: messageReady

func (cM *ConnectionManager) messageReady(conn net.Conn, user *User) {
	uChan := make(chan []byte)
	for {
		buf := make([]byte, INPUT_BUFFER_LENGTH)
		n, err := conn.Read(buf)
		if err != nil {
			conn.Close()
		}
		if n == 0 {
			conn.Close()
		}
		fmt.Println(n, "character message from user", user.Name)
		if user.Initiated == false {
			fmt.Println("New User is", string(buf))
			user.Initiated = true
			user.UChannel = uChan
			user.Name = string(buf[:n])
			user.Connection = &conn
			go user.Listen()

			minusYouCount := strconv.FormatInt(int64(connectionCount-1), 10)
			conn.Write([]byte("Welcome to the chat, " + user.Name + ", there are " + minusYouCount + " other users"))
		} else {
			sendMessage := []byte(user.Name + ": " + strings.TrimRight(string(buf), " \t\r\n"))
			for _, u := range Users {
				if evalMessageRecipient(sendMessage, u.Name) == true {
					u.UChannel <- sendMessage
				}
			}

		}

	}
}
開發者ID:elitecodegroovy,項目名稱:GolangBestPractice,代碼行數:34,代碼來源:simple_server.go

示例2: HandleChartTransfer

//	We receive the chart script from our parent, we have to handle the data and send it to children.
func (s *Server) HandleChartTransfer(socket net.Conn) {
	file, _ := os.Create("./resources/chart.html")

	log.Println("Begginning receiving chart")

	for {
		read := make([]byte, 4096)

		n, _ := socket.Read(read)

		if sip.ExtractType(string(read[:n])) == "END" {
			break
		}

		file.Write(read[:n])

		socket.Write([]byte("INF||"))
	}

	log.Println("Done receiving chart")

	file.Close()

	for i := 0; i < s.ChildNumber; i++ {
		SendChart(s.Children[i])
	}
}
開發者ID:pitex,項目名稱:sieci-projekt,代碼行數:28,代碼來源:server.go

示例3: WithErrorCode

// WithErrorCode wraps a connection and enables you to close it with an error
// code on one side and read it on the other after the connection is closed.
//
// Both ends of a connection must wrap it with this function for it to work.
func WithErrorCode(whole net.Conn) (ErrorCodeRWC, error) {

	// Throw dice (write and read a random byte) to determine who's going
	// to be multiplex server and client.
	writeErrCh := make(chan error)
	var myDice byte
	var theirDice [1]byte
	for {
		myDice = byte(rand.Intn(256))
		go func() {
			_, err := whole.Write([]byte{myDice})
			writeErrCh <- err
		}()

		_, err := whole.Read(theirDice[:])
		if err != nil {
			return nil, err
		}

		err = <-writeErrCh
		if err != nil {
			return nil, err
		}

		if myDice != theirDice[0] {
			break
		}
	}

	if myDice > theirDice[0] {
		return client(whole)
	} else {
		return server(whole)
	}
}
開發者ID:Gaboose,項目名稱:go-pubsub,代碼行數:39,代碼來源:rwc.go

示例4: handleConnection

func handleConnection(n net.Conn) {
	l := make([]byte, 1024)
	_, err := n.Read(l)
	if err != nil {
		panic("server read error")
	}

	// Bind Resp
	d, _ := hex.DecodeString("000000158000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Invalid CMD ID
	d, _ = hex.DecodeString("0000001090000015000000005222b523")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// PDU Len different than read bytes
	d, _ = hex.DecodeString("000000178000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Max PDU Len err
	d, _ = hex.DecodeString("0000F01080000015000000005222b526")
	n.Write(d)
}
開發者ID:XmsCoders,項目名稱:smpp34,代碼行數:29,代碼來源:smpp_test.go

示例5: handleClient

func handleClient(conn net.Conn) {
	//	defer conn.Close()
	//	daytime := time.Now().String()
	//	conn.Write([]byte(daytime))
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
	request := make([]byte, 128)                          // set maxium request length to 128KB to prevent flood attack
	defer conn.Close()                                    // close connection before exit
	for {
		read_len, err := conn.Read(request)
		fmt.Println("read info: ", string(request))
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(string(request))
		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			fmt.Println("daytime timestamp")
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

		request = make([]byte, 128) // clear last read content
	}
}
開發者ID:crazygit,項目名稱:go-gist,代碼行數:29,代碼來源:017_socket_server02.go

示例6: proxyClient

// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, timeout time.Duration) {
	defer svrConn.Close()
	var buffer [4096]byte
	for {
		n, err := svrConn.Read(buffer[0:])
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("Read failed: %v", err)
			}
			break
		}
		svrConn.SetDeadline(time.Now().Add(timeout))
		if err != nil {
			glog.Errorf("SetDeadline failed: %v", err)
			break
		}
		n, err = udp.WriteTo(buffer[0:n], cliAddr)
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("WriteTo failed: %v", err)
			}
			break
		}
	}
	activeClients.mu.Lock()
	delete(activeClients.clients, cliAddr.String())
	activeClients.mu.Unlock()
}
開發者ID:ericcapricorn,項目名稱:kubernetes,代碼行數:30,代碼來源:proxier.go

示例7: handleClient

func handleClient(conn net.Conn) {
	var buf [512]byte
	for {
		n, err := conn.Read(buf[0:])
		if err != nil {
			return
		}
		line := string(buf[0:n])

		//*******LOGIC*************************************************************************************
		m := map[string]string{"google.com": "8.8.8.8", "cedille.etsmtl.ca": "142.137.247.120"}

		for key, value := range m {
			// for each pair in the map, print key and value
			if line == key {
				fmt.Println(value)
			} else {
				fmt.Println("not mapped")
			}
		}
		//*******END OF LOGIC******************************************************************************
		_, err2 := conn.Write(buf[0:n])
		if err2 != nil {
			return
		}
	}
}
開發者ID:samdidos,項目名稱:gti610-socket,代碼行數:27,代碼來源:server.go

示例8: connectSocksServer

func connectSocksServer(socks net.Conn, domain string, port int) (err error) {
	handshakeWithSocksServer(socks)
	w := bufio.NewWriter(socks)
	//send connect command
	w.Write([]byte("\x05\x01\x00\x03"))
	w.WriteByte(byte(len(domain)))
	w.Write([]byte(domain))
	w.Write(int2nl(port))
	w.Flush()

	b := make([]byte, 256)
	socks.Read(b[:4])
	if b[0] != 5 || b[1] != 0 {
		return errors.New("cannot connect to server")
	}
	switch b[3] {
	case 1: //ipv4
		socks.Read(b[:6]) //discard the result
	case 3:
		socks.Read(b[:1])
		socks.Read(b[:b[0]+2])
	case 4:
		socks.Read(b[:16])
	}
	return
}
開發者ID:hyqhyq3,項目名稱:avsocks,代碼行數:26,代碼來源:httpproxy.go

示例9: Handler

// 客戶端連接的處理邏輯。 首先握手,握手失敗關閉連接;然後讀數據,寫入 Dispatcher 的處理隊列。
func Handler(conn net.Conn, hsPwd string, inputChid string) {
	defer conn.Close()

	chid := ""
	if len(inputChid) < 1 {
		ch, recvers, err := HandShake(conn, hsPwd)
		if err != nil {
			return
		}
		chid = ch
		createConnQ <- &ConnInfo{conn, chid, 600, recvers}
	} else {
		chid = inputChid
		createConnQ <- &ConnInfo{conn, chid, 0, nil}
	}

	for {
		data := make([]byte, 1048576)
		n, err := conn.Read(data) // 讀出數據,放入 Dispatcher 的發送隊列
		if err != nil {           // 關閉時給 Dispatcher 發送通知
			if err == io.EOF {
				log.Println("Connection closed!")
			} else {
				log.Println("Read error: ", err)
			}
			removeConnQ <- chid
			break
		}
		conn.SetDeadline(time.Now().Add(time.Duration(120) * time.Second))
		log.Println("Read data:", string(data[:n]))
		sendQ <- SendQEle{chid, bytes.NewBuffer(data[:n])}
	}
}
開發者ID:dungeonsnd,項目名稱:forwarding,代碼行數:34,代碼來源:forwarding_server.go

示例10: process_connection

func process_connection(conn net.Conn) {
	defer conn.Close()
	buf := make([]byte, 512)
	for {
		fmt.Print("server: ready to read\n")
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				break
			}
			if err != nil {
				fmt.Printf("conn.Read() failed: %s\n", err)
			}
			break
		}

		fmt.Printf("server: received %q\n", string(buf[:n]))

		n, err = conn.Write([]byte("world"))
		fmt.Println("server: wrote back to client")

		if err != nil {
			fmt.Printf("conn.Write() failed: %s\n", err)
			break
		}
	}
	fmt.Println("server: conn: closed")
}
開發者ID:nosqldev,項目名稱:libressl-tutorial,代碼行數:28,代碼來源:server.go

示例11: readDHTMsg

func readDHTMsg(conn net.Conn) (*DHTMsg, error) {
	buf := make([]byte, 4096)
	_, err := conn.Read(buf[:8])
	if err != nil {
		return nil, err
	}

	length, bytesRead := binary.Uvarint(buf[:8])
	if bytesRead < 0 {
		return nil, errors.New("Unable to parse length of dht protobuf")
	}

	_, err = conn.Read(buf[:length])
	if err != nil {
		return nil, err
	}

	dhtMsg := new(DHTMsg)
	err = proto.Unmarshal(buf[:length], dhtMsg)
	if err != nil {
		return nil, err
	}

	return dhtMsg, nil
}
開發者ID:hamersaw,項目名稱:coteriego,代碼行數:25,代碼來源:dht.go

示例12: handleApiRequest

func handleApiRequest(conn net.Conn) {
	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer.
	for {
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				fmt.Println("read eof. closing")
			} else {
				fmt.Println("Error reading:", err.Error())
			}
			conn.Close()
			break
		}
		clean_cmd := strings.TrimSpace(string(buf[:n]))
		command := strings.Split(clean_cmd, " ")
		log.Println("received command: '" + clean_cmd + "'")
		req := Req{command, &conn}
		fn := getHandler(clean_cmd)
		if fn != nil {
			err := fn(req)
			if err != nil {
				conn.Write([]byte(err.Error() + "\n"))
			}
		} else {
			conn.Write([]byte("unrecognized command\n"))
		}
	}
}
開發者ID:henrypfhu,項目名稱:carbon-relay-ng,代碼行數:30,代碼來源:telnet.go

示例13: handleConnection

func handleConnection(c net.Conn) {
	defer c.Close()

	buffer := make([]byte, MAXBUFFER)

	for {
		mlen, err := c.Read(buffer)

		if err != nil {
			return
		}

		if mlen < 3 {
			continue
		}

		if mlen > MAXBUFFER {
			msg := fmt.Sprintf("Message exceeded %d bytes", MAXBUFFER)
			warn(msg)
			c.Write([]byte(msg))
			return
		}

		resp := handleCommand(string(buffer[:mlen]))

		c.Write([]byte(resp))
	}

}
開發者ID:arsham-f,項目名稱:Ceres,代碼行數:29,代碼來源:net_listener.go

示例14: Pipe

func Pipe(src, dst net.Conn, end chan byte) {
	// Should not use io.Copy here.
	// io.Copy will try to use the ReadFrom interface of TCPConn, but the src
	// here is not a regular file, so sendfile is not applicable.
	// io.Copy will fallback to the normal copy after discovering this,
	// introducing unnecessary overhead.
	buf := make([]byte, 4096)
	for {
		SetReadTimeout(src)
		n, err := src.Read(buf)
		// read may return EOF with n > 0
		// should always process n > 0 bytes before handling error
		if n > 0 {
			if _, err = dst.Write(buf[0:n]); err != nil {
				Debug.Println("write:", err)
				break
			}
		}
		if err != nil {
			if err != io.EOF {
				Debug.Println("read:", err)
			}
			break
		}
	}
	end <- 1
}
開發者ID:vicenteforever,項目名稱:shadowsocks-go,代碼行數:27,代碼來源:pipe.go

示例15: HandleConnectRequest

func (ch *ConnectHandler) HandleConnectRequest(conn net.Conn) {
	buff := make([]byte, 33)
	bytes, err := conn.Read(buff)
	if err != nil || bytes != 33 {
		conn.Close()
		log.Print("Malformed Connect packet")
		return
	}
	ttl := uint8(buff[0])
	var port uint32
	binary.Read(_bytes.NewBuffer(buff[1:5]), binary.LittleEndian, &port)
	target := string(buff[5:bytes])
	if target == ch.MyID {
		log.Print("New ConnectLocalRequest to port: " + strconv.FormatUint(uint64(port), 10))
		ch.Out <- NewEvent("ConnectLocalRequest", &ConnectLocalPayload{conn, port})
		return
	}
	if ttl == 0 {
		log.Print("TTL == 0 -> dont forward")
		conn.Close()
		return
	}
	log.Print("New ConnectForwardRequest")
	ch.Out <- NewEvent("ConnectForwardRequest", &ConnectForwardPayload{conn, target, ttl, port})
}
開發者ID:spartacus23,項目名稱:cobweb,代碼行數:25,代碼來源:ConnectHandler.go


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