0

In C code I have written a sub-function called read_ascii(data, recv_buf, &flag_end) to read the character from data to buffer recv_buf. In the main program:

int socket_in , new_sd , cc, go, flag_end;
struct sockaddr_in server , client;
char recv_buf[1024];
cc = sizeof(struct sockaddr_in);
data = accept(socket_in, (struct sockaddr *)&client, (socklen_t*)&cc);
while(1)
{ read_ascii(data, recv_buf, &flag_end);
  if (strncmp(recv_buf, "A", 1) == 0)
        {
        printf ("A");
        write(data, "ok", 2);
        }
  else if (strncmp(recv_buf, "B", 1) == 0)
        {
        printf ("B");
        write(data, "ok", 2);
        }
  else 
        {
        write(data, "FAIL", 4);
        }
  }

In Python I know that no need to read the character like C, we can define recv_buf = "\0" * 1024 -- according to this.

But it seems thats the recv_buf buffer is overwritten each time I read the value of TCP/IP

while True:
   c, addr = server_tcp.accept()     # Establish connection with client.
   data = server_tcp.recv(1024)
   if 'A' == data 
        n=server_tcp.send('OK')
   elif 'B'== data
        n=server_tcp.send('OK')
   else:
        print ('I did not get the right command DEF')
   break
 server_tcp.close()

Therefore when the client send B then A, I did get the good answer from server (OK, OK) that i supposed. Any help would be appreciated. Thank you

Axe319
  • 4,255
  • 3
  • 15
  • 31
fpga
  • 11
  • 1
  • 4
  • 1
    Are you referring to `data`? In any case, it is really important to understand, a Python `str` will not act like a C array of chars. Importantly, `str` objects are *immutable*. Also, in Python, `x = y` **never mutates** – juanpa.arrivillaga Oct 25 '21 at 10:17
  • You probably want to just use a `list`, or perhaps, a `bytearray`, and use the respective *append* methods – juanpa.arrivillaga Oct 25 '21 at 10:19

0 Answers0