LINUX C++ 多執行序 網路 (LINUX multi thread socket server)
LINUX C++ 多執行序 網路 (LINUX multi thread socket server)
資料來源:http://www.tidytutorials.com/2010/06/linux-c-socket-example-with-client.html
LinServer.cpp
#include <fcntl.h> void* SocketHandler(void*); int main(int argv, char** argc){ int host_port= 1101; struct sockaddr_in my_addr; int hsock; socklen_t addr_size = 0;
hsock = socket(AF_INET, SOCK_STREAM, 0); my_addr.sin_family = AF_INET ; //Now lets do the server stuff addr_size = sizeof(sockaddr_in); void* SocketHandler(void* lp){ char buffer[1024]; memset(buffer, 0, buffer_len); if((bytecount = send(*csock, buffer, strlen(buffer), 0))== -1){
FINISH: |
LinClient.cpp
#include <fcntl.h> int main(int argv, char** argc){ int host_port= 1101; struct sockaddr_in my_addr; char buffer[1024]; int hsock; hsock = socket(AF_INET, SOCK_STREAM, 0); my_addr.sin_family = AF_INET ; if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){ //Now lets do the client related stuff buffer_len = 1024; memset(buffer, ‘\0’, buffer_len); printf(“Enter some text to send to the server (press enter)\n”); if((bytecount = recv(hsock, buffer, buffer_len, 0))== -1){ close(hsock); |
g++ -o server LinServer.cpp -lpthread
g++ -o client LinClient.cpp