-1

Still trying to understand the send() and recv() functions. Why isn't this working? Nothing prints out on the server output.(except for some Test "cout"s)

This is basically the part of the code I'm messing with.

CLIENT SIDE:

char *mesg_to_send;   
Socket servSock;
mesg_to_send = The King is Dead!";
// Establish the connection to the echo server 
if(connect(servSock, (struct sockaddr *) &srvr_addr, sizeof(srvr_addr)) < 0)  
  DieWithError("connect() failed");
send(servSock, (char*) mesg_to_send, sizeof(int), 0);

SERVER SIDE:

char *sentence;
Socket clnt_socket;
// Wait for the client to connect
if((clnt_socket = accept(srvr_socket, (struct sockaddr *) &clnt_addr, &addr_len)) < 0)
  DieWithError("accept() failed");
recv(clnt_socket, (char*) sentence, sizeof(int), 0);
cout << sentence;
MikO
  • 18,243
  • 12
  • 77
  • 109
joetaiijo
  • 1
  • 1

1 Answers1

0

Right away, you have several problems in your code, and that's besides a syntax error (did you mean to have an opening quote right before The King?). Did you really compile and test the same code that you posted?

  • Instead of sending the entire sentence, you are sending only the first sizeof(int) bytes. Since sizeof(int) is likely 4 on your platform, that means you are probably sending only "The ".

  • Similarly, you are only reading sizeof(int) bytes from the client on the server. You probably instead want to read into a larger buffer, and keep reading in a loop for as long as the client sends data (i.e. for as long as you don't read EOF).

  • What data type is Socket? Socket file descriptors are supposed to be kept in variables of type int.

  • On the server side, you don't initialize the sentence buffer. At the time that you pass it to recv, it is an uninitialized pointer, likely pointing to random memory.

  • You also may not be initializing addr_len on the server (it should be initialized to sizeof(clnt_addr) before the call to recv).

Celada
  • 21,627
  • 4
  • 64
  • 78