MultiThreaded Server

Hello rrybody,
Im trying to create a server that handles more than one client at a time. It allows a client to connect and the client receives the message the server but right after i get a invalid argument error when trying to accept a new client. Please help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* A simple server in the internet domain using TCP
 The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>

#include <pthread.h>
#include <string>

using namespace std;

void *HandleSocket( void *Something);

void error(const char *msg)
{
    perror(msg);
    exit(1);
}


int main(int argc, char *argv[])
{
    pthread_t ThreadSockets[10];
    
    int sockfd;
    socklen_t clilen;
    
    char buffer[256];
    bzero(buffer, 256);
        
    struct sockaddr_in serv_addr, cli_addr;
    
    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    //fcntl(sockfd, F_SETFL, O_NONBLOCK); //gets resource temporarily unavailable on accept 
    if (sockfd < 0)
        error("ERROR opening socket");
    
    bzero((char *) &serv_addr, sizeof(serv_addr));
    
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(5000);
    
    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
        error("ERROR on binding");
    
    listen(sockfd,10);
    clilen = sizeof(cli_addr);
    
    //write(sockfd, "Test", 6);

    
    while (1)
    {
        sockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
        if (sockfd < 0)
            error("ERROR on accept");
        pthread_create(&ThreadSockets[0], NULL, HandleSocket, (void*)sockfd);
        pthread_join(ThreadSockets[0], NULL);
    }
    
    //for (int i = 0; i != Connected; i++)
      //  close(Clients[i]);
    
    close(sockfd);
    return 0;
}

void *HandleSocket( void *Something)
{
    string Msg = "Test from thread";
    int CurClient = (intptr_t)Something;
    write(CurClient, &Msg, Msg.length()); //Only receives "Test from threa"
    return 0;
}
Topic archived. No new replies allowed.