本文整理汇总了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
}
}
}
}
}
示例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])
}
}
示例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)
}
}
示例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)
}
示例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
}
}
示例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()
}
示例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
}
}
}
示例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
}
示例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])}
}
}
示例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")
}
示例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
}
示例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"))
}
}
}
示例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))
}
}
示例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
}
示例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})
}