Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdlib.h>
- #include<stdio.h>
- #include<sys/types.h>
- #include<sys/socket.h>
- #include<netinet/in.h>
- #include<string.h>
- #include<pthread.h>
- void* serve_request(void* newsockfdptr)
- {
- printf("Thread started\n");
- char buffer[256];
- int n;
- int newsockfd=*((int*)newsockfdptr);
- /*if connection established then start communicating*/
- bzero(buffer, 256);
- n=read(newsockfd, buffer, 255);
- if(n<0)
- {
- perror("Error reading from socket");
- }
- printf("Here is the message: %s\n",buffer);
- /*write response to the client*/
- n=write(newsockfd,"I got your message", 18);
- if(n<0)
- {
- perror("Error writing to socket");
- exit(1);
- }
- close(newsockfd);
- printf("Thread ended\n");
- }
- int main(int argc, char* argv)
- {
- pid_t pid;
- pid=fork();
- if(pid!=0)
- exit(0);
- int sockfd, newsockfd, portno, clilen;
- char buffer[256];
- struct sockaddr_in serv_addr, cli_addr;
- int n;
- pthread_t temp;
- /*first call to socket function*/
- sockfd=socket(AF_INET, SOCK_STREAM, 0);
- setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, 0, 0);
- if(sockfd<0)
- {
- perror("Error opening socket");
- exit(1);
- }
- /*initialize socket structure*/
- bzero((char*)&serv_addr, sizeof(serv_addr));
- portno=5001;
- serv_addr.sin_family=AF_INET;
- serv_addr.sin_addr.s_addr=INADDR_ANY;
- serv_addr.sin_port=htons(portno);
- /*now bind the host address using bind() call.*/
- if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr))<0)
- {
- perror("Error on binding");
- exit(1);
- }
- /*now start listening for the clients, here process will
- go in sleep mode and will wait for the incoming connection*/
- listen(sockfd, 5);
- clilen=sizeof(cli_addr);
- while(1)
- {
- /*accept actual connection from the client*/
- newsockfd=accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
- if(newsockfd<0)
- {
- perror("Error on accept");
- exit(1);
- }
- pthread_create(&temp,NULL,serve_request, &newsockfd);
- //serve_request(newsockfd);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement