0
I could use a little help with sockets
in C. My teacher passed a job in which I must perform communication TCP
between client and server where I must execute some rules..
- 1 - The Client sends a message to the server. The message must contain the sequence number and amount of bytes loaded by message.
- 2 - The server must receive the message and send an acknowledgement to the client. The recognition message shall contain the number of sequence of the recognition message means the sequence number of the next segment to be sent by the customer.
Could someone please explain to me how the sequence number works and if possible help me encode it? The client/server TCP communication part is attached and ready.
Snippet of client code:
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
gets(message);
fflush(stdin);
//scanf("%s" , message);
//Send some data
if( send(sock , message, strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
//puts(server_reply);
int vl = 0;
for(int i =0; server_reply[i] != '\0';i++)
{
if(server_reply[i] != ' ')
vl += (int)server_reply[i];
}
printf("%d\n",vl);
}
close(sock);
Chunk of server code:
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
//Send the message back to client
write(client_sock , client_message , strlen(client_message));
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}