简体   繁体   中英

Server not receiving Data from TCP Client in GO

Hello I have implemented a server in GO which reads data from a client and print it. For reading from the network stream, I am reading from the conn.Read() method on server.

Below is my code to read a byte from network stream

// return a single byte after reading from buffer
func readByte(conn net.Conn,buf []byte,numberofbytes *int,bufCurrPos *int) (byte){
    fmt.Printf("Byte read")
    if *bufCurrPos == *numberofbytes {
        for {
                *bufCurrPos = 0
                *numberofbytes,_ = conn.Read(buf)
                if *numberofbytes ==0 {
                continue
            } else {
                break
            }
        }
    }
    b := buf[*bufCurrPos]
    *bufCurrPos++
    return b
}

Now I have created two client which write data to server.

First Client write to the stream using conn.Write() method while second method write to the stream using fmt.Fprintf(bufio.NewWriter(),format string) method.

Client 1

conn, err := net.Dial("tcp","localhost:8080")
if err != nil {
    checkError(err)
}
go readHandler(conn)
for {
    reader := bufio.NewReader(os.Stdin)
    text, _ := reader.ReadString('\n')
    conn.Write([]byte(text[0:len(text)-1]+"\r\n"))
}

client 2 :

name := "hi.txt"
        contents := "bye"
        exptime := 300000
        conn, err := net.Dial("tcp", "localhost:8080")
        if err != nil {
                t.Error(err.Error()) // report error through testing framework
        }
        scanner := bufio.NewScanner(conn)

        // Write a file

        n,err := fmt.Fprintf(bufio.NewWriter(conn), "write %v %v %v\r\n%v\r\n", name, exptime, len(contents), contents)
        if err !=nil {
                fmt.Printf("error in writing in buffer\n")
        }

Server read the data properly with first client but for the second client, it just read 0 byte always.

I am begginer in GO and don't know the reason for that. Could somebody please help me in that

The client2 application must flush the buffer.

bw := bufio.NewWriter(conn)
n,err := fmt.Fprintf(bw, "write %v %v %v\r\n%v\r\n", name, exptime, len(contents), contents)
bw.Flush()

The application should also check errors.

bw := bufio.NewWriter(conn)
_, err := fmt.Fprintf(bw, "write %v %v %v\r\n%v\r\n", name, exptime, len(contents), contents)
if err != nil {
     // handle error
}
if err := bw.Flush(); err != nil {
     // handle error
}

fmt.Fprintf buffers internally. If this is the only write to the connection, then remove the buffered writer.

_, err := fmt.Fprintf(conn, "write %v %v %v\r\n%v\r\n", name, exptime, len(contents), contents)
if err != nil {
    // handle error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM