Multi-thread example of http://forums.devshed.com socket

Source: Internet
Author: User
Http://forums.devshed.com/c-programming-42/i-need-a-multi-thread-socket-server-source-to-refer-to-91703.html
# Include <my_sock.h>
# Include <errno. h>

# Define port 6969
# Define bufsize 8192
# Define perm (s_irusr | s_iwusr | s_irgrp | s_iroth)
# Define maxthreads 25

Void * f00 (void * Data)
{
Char Buf [bufsize];
Int asock = (INT) data, nread = 0, FD = 0;

// Open the file
If (FD = open ("tmp", o_creat | o_trunc | o_wronly, Perm) <0)
Err_quit ("open ");

// Read from socket, write to file
While (nread = read (asock, Buf, bufsize)> 0)
If (write (FD, Buf, nread )! = Nread)
Err_quit ("write ");

Close (FD );
Return;
};

Int main (INT argc, char ** argv)
{
Int on = 1, FD = 0, lsock = 0, asock = 0, nread = 0, nthreads = 0, x = 0;
Char Buf [bufsize];
Struct sockaddr_in SA;
Socklen_t Len = sizeof (SA );
Pthread_t threadid [maxthreads];

// Initialize the socket -- returns <0 on Error
If (lsock = socket (af_inet, sock_stream, 0) <0)
Err_quit ("socket ");

If (setsockopt (lsock, sol_socket, so_reuseaddr, & on, sizeof (on) <0)
Err_quit ("setsockopt ");

// Setup the sock_addrin Structure
Memset (& SA, 0, sizeof (SA ));
SA. sin_family = af_inet;
SA. sin_port = htons (port );
SA. sin_addr.s_addr = htonl (inaddr_any );

// Bind socket
If (BIND (lsock, (struct sockaddr *) & SA, sizeof (SA) <0)
Err_quit ("bind ");

// Go into Listen Mode
If (Listen (lsock, 5) <0)
Err_quit ("listen ");

While (1 ){
// Accept a connection
If (asock = accept (lsock, null, null) <0)
Err_quit ("accept ");

// Spawn a thread for each clien
If (pthread_create (& threadid [x ++], null, (void *) & f00, (INT) asock )! = 0)
Perr_quit ("pthread ");

If (nthreads ++> = maxthreads)
Break;
}

// Wait for all threads
For (x = 0; x <nthreads; X ++)
If (pthread_join (threadid [X], null) <0)
Perr_quit ("pthread join ");

// Cleanup
Close (lsock );

Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.