Skip to content

Instantly share code, notes, and snippets.

@CreatiCoding
Last active August 10, 2018 08:52
Show Gist options
  • Save CreatiCoding/004f7b7746eee0528bc24189105b0bea to your computer and use it in GitHub Desktop.
Save CreatiCoding/004f7b7746eee0528bc24189105b0bea to your computer and use it in GitHub Desktop.
tcp socket one increase server with multi thread c++11
#include <cstdio>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <iostream>
#include <thread>
using namespace std;
void error(const char *message){
perror(message);
exit(1);
}
void increase_thread(void* lp){
int *client_socket = (int*)lp;
int check = 0;
int output = 0;
while(true){
char buffer[256] = { 0 };
check = read(*client_socket,buffer,256);
if(check <= 0) {
cout << "disconnect, client exited." << endl;
close(*client_socket);
return;
}else if(string("exit").compare(buffer) == 0){
cout << "client exited." << endl;
close(*client_socket);
return;
}else if(string("shutdown").compare(buffer) == 0){
cout << "server will shutdown." << endl;
write(*client_socket,"shutdown",9);
close(*client_socket);
terminate();
return;
}
string message;
try {
output = stoi(buffer) + 1;
cout<<"client: "<<buffer<<endl;
cout<<"result: "<<output<<endl;
message=to_string(output);
} catch(...) {
message="Try again, input number.";
}
check=write(*client_socket,message.c_str(),message.length());
if(check<0){
cout << "disconnect, client exited." << endl;
close(*client_socket);
return;
}
}
}
int main(int argc,char **argv){
if(argc<2) error("argument is port.");
int server_socket;
int *client_socket;
int port;
socklen_t client_socket_length;
struct sockaddr_in server_addr,client_addr;
int queue_length;
int check;
port=atoi(argv[1]);
queue_length=128;
server_socket=socket(AF_INET,SOCK_STREAM,0);
if(server_socket<0) error("error occurs in opening server_socket");
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=INADDR_ANY;
server_addr.sin_port=htons(port);
check = bind(server_socket,(struct sockaddr *)&server_addr,sizeof(server_addr));
if(check<0) error("error occurs in binding");
check = listen(server_socket,queue_length);
if(check<0) error("error occurs in listening");
while(true){
client_socket_length=sizeof(client_addr);
client_socket=new int;
*client_socket = accept(server_socket,(struct sockaddr *)&client_addr,&client_socket_length);
if(*client_socket<0){
error("error occurs in accepting");
} else {
thread t(increase_thread,(void*)client_socket);
t.detach();
cout<<"client enters."<<endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment