I
I
Ivan Ivanoff2020-01-21 23:08:52
go
Ivan Ivanoff, 2020-01-21 23:08:52

How to send message from server to client?

Hello!
There is a listener (goroutine) that listens for a connection with a client
. It has this:

var buffer = make([]byte, 1024)

  for {
    bytesRead, err := conn.Read(buffer)
    if err != nil {
      conn.Close()
      return
    }
    var s = string(buffer[:bytesRead])
                //тут всякие действия в зависимости от приходящих значений
         }


Goroutine perfectly listens to incoming data and performs the necessary actions, and even writes what is needed in response to the socket,
but in this cycle, take it yourself and fire something to the client, bypassing waiting for data from it?
Or is it basically impossible?

When trying to write something to the socket out of queue, the script crashes with an error writing to a closed connection.

I would appreciate your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2020-01-22
@Thoth777

In order to send something, someone on the other side must receive. Judging by your mistake, the client closes the connection, and then nothing can be sent. We must first teach the client not to break the connection, but to continue to wait for new data, then the problem will disappear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question