HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Socket client in C using threads

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threadsclientsocketusing

Problem

I'm working on socket programming in C. I have no problem with usage the threads. This all works fine but I'm new in this area. I wrote this code in client.c but is there any misused code or something may cause problems in the future?

My client sends a message to the server and client can receive it. There are 2 major operations: recv and send.
CLIENT

```
#include
#include
#include // for inet_addr
#include
#include
#include
#include

void sendMessage(void sock_desc) {
//Send some data
while (1) {
char message[2000];
printf("%s","> ");
scanf("%[^\n]%*c", message);
fflush(stdin);

if (send(((int ) sock_desc), message, strlen(message) + 1, 0) < 0) {
puts("Send failed");
}
}
}

void receiveMessage(void sock_desc) {
while (1) {
char server_reply[2000];
if (recv(((int ) sock_desc), server_reply, 2000, 0) < 0) {
puts("recv failed");

}
//Receive a reply from the server
printf("\033[32;1m %s \033[0m\n", server_reply);
}
}

int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
//char message[2000], server_reply[2000];

//Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Could not create socket");
}

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 to server\n");
int *new_sock;
new_sock = malloc(1);
*new_sock = sock;
//keep communicating with server

pthread_t send_thread, receive_thread;
pthread_create(&send_thread, NULL, sendMessage, (void *) new_sock);
pthread_create(&receive_thread, NULL, receiveMessage, (void *) new_s

Solution


  • You have to allocate sizeof(int) bytes for socket file descriptor, not 1



  • fflush(stdin) has undefined behavior



  • its not good idea to access a file descriptor in two threads simultaneously, be careful



  • joins are never happens, because none of two threads have exit conditions, so the socket will never close gracefully

Context

StackExchange Code Review Q#151044, answer score: 2

Revisions (0)

No revisions yet.