L
L
loparenok2021-08-04 11:00:21
go
loparenok, 2021-08-04 11:00:21

Why can't I exchange data via net.Conn?

The client and the server exchange some information, after receiving a request from the server, the client sends a file to the server via net.Conn. And after sending the file, when trying to read the next message by the server from the client, I get the first line of the file transferred earlier.
Code for reading messages on the server:

func get_message_from_client(c net.Conn) string {
  message, _ := bufio.NewReader(c).ReadString('\n')
  message = strings.TrimSpace(message)
  write_log("Получено сообщение от клиента: ", message)
  return message
}

Code for receiving a file on the server:
func save_file(file_size int64, file_path string, c net.Conn) {
  write_log("получаем файл от клиента: ", file_path)
  newfile, err := os.Create(file_path)
  if err != nil {
    write_log("не удалось создать файл: ", file_path)
    fmt.Println(err)
  }
  defer newfile.Close()

  var BUFFERSIZE int64
  var receivedBytes int64

  BUFFERSIZE = 1024

  for {
    if (file_size - receivedBytes) < BUFFERSIZE {
      io.CopyN(newfile, c, (file_size - receivedBytes))
      c.Read(make([]byte, (receivedBytes+BUFFERSIZE)-file_size))
      break
    }
    io.CopyN(newfile, c, BUFFERSIZE)
    receivedBytes += BUFFERSIZE
  }
}

Functions are called sequentially,
for {
   message := get_message_from_client(c)
   if message == "FILE" {
      save_file(file_save.size, new_name_file, c)
      send_message(c, "PASS")
   }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-08-04
@loparenok

First, when you create a buffer reader and read the string bufio.NewReader(c).ReadString('\n'), the reader can actually read much more than one line, which is why it's a buffer.
If you want to use bufio, then create a reader once and then pass it everywhere in the code and read only from it, and not from net.Conn
Secondly, somehow you wrote the file receipt very complicated, the error is most likely there.
This is all better done using the standard library:

limited := io.LimitReader(c, file_size)
err = io.Copy(newfile, limited)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question