How to mark end of write to TCP server from client

I am writing a TCP client which is supposed to talk to remote TCP server( some HSM server) and get the response back. When I tried to write to the client, I am not able to convey to the server that write stream has ended.
Is there any way to do that.

What do you mean by you are “not able to convey to the server that write stream has ended”?

Can you provide some example code?

Unless you intend to only ever send one message over the connection you need some sort of framing to tell the receiver where one message ends and the next begins. Typically this is done by adding a length word at the beginning of the message (and maybe a type or other metadata). The receiver then does things in two passes: read the length word, read as many bytes as the length says, repeat.

1 Like

Actually, I got it solved by doing the following:
I had to explicitly close the writer before reading the reply back.

    func (t *someStruct) Execute(command string) ([]byte, error) {
	addr := &net.TCPAddr{
		IP:   t.ip,
		Port: t.port,
	}
	conn, err := net.DialTCP("tcp", nil, addr)
	defer conn.Close()
	if err != nil {
		fmt.Println("Failed?")
		return nil, err
	}
	conn.SetNoDelay(true)
	req := []byte("")
	req = append(req, []byte(command)...)
	_, err = conn.Write(req)
	conn.CloseWrite()
	if err != nil {
		return nil, err
	}
	res, err := ioutil.ReadAll(conn)
	if err != nil {
		return nil, err
	}
	return res, nil
}

Thanks

Yeah, that’s the other “unless you intend to only ever send one message” side of it. :wink:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.