TCP - I need to dial before sending each message

I want a client and server that can exchange messages back and forth.

Currently, the client dials and sends a greeting.
The server accepts the connection and answers 3 times.

The client only hears the first answer, then doesn’t seem to receive the other two, unless the server dials to the client before sending those too.

Is that how TCP is supposed to work?
If not, why does the client only accept one message?

Terminal output…
(server)
heard
2022/03/21 01:43:16
newClient
Dialing
sending msg
sending 2nd msg
sending 3rd msg

(client)
preAccept
accepted 127.0.0.1:53047
postAccept
preAccept
2022/03/21 01:43:20 rcv: msg

Code…
server

client

I solved it by having the client listen to the dial for the messages, instead of using its own Listen function.

 
        buf := make([]byte, 1024)
        n, _ := c.Read(buf)
    got := string(buf[:n])
    log.Print("rcv: "+got)
        return
  }
 

The problem is that handleMessage only reads a single message from each connection.

You want someting like

func handleMessage(c net.Conn){
	buf := make([]byte, 1024)
	for {
		n, err  := c.Read(buf)
		if err != nil {
			break
		}
		log.Print("rcv: %s ", buf[:n])
	}
	c.Close()
}

But, of course, TCP/IP is a streaming protocol.
so the message boundaries of the received messages may be different
from the boundaries that are sent.

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