TCP Server that handles multiple client requests at the same time by using multiple threads
Dependents: ThreadServer Server_Multi_Client
Server.cpp
- Committer:
- lemniskata
- Date:
- 2013-06-11
- Revision:
- 1:e1db78d5ccc1
- Parent:
- 0:a5fdd089d5c6
- Child:
- 2:1b1f3ab29984
- Child:
- 4:c57a998796ae
File content as of revision 1:e1db78d5ccc1:
/* ** File name: Server.cpp ** Descriptions: TCP server that handles multiple client requests in separate threads ** **------------------------------------------------------------------------------------------------------ ** Created by: Ivan Shindev ** Created date: 06/11/2013 ** Version: 1.0 ** Descriptions: The original version ** **------------------------------------------------------------------------------------------------------ ** Modified by: ** Modified date: ** Version: ** Descriptions: ********************************************************************************************************/ #include "Server.h" #include "mbed.h" /*Handle_client handles the client request * * Default: Echo the clients request */ void Handle_client(void const *socket_data) { int socket; char buffer[256]; socket = (int)socket_data; int n = lwip_recv(socket ,buffer,sizeof(buffer),0); //read from the client if (lwip_send(socket ,buffer,n,0)!=n) //send the content back to the socket { } } osThreadDef(Handle_client, osPriorityNormal, DEFAULT_STACK_SIZE); Server::Server(int port, int max_number_of_clients): _port(port), _max_number_of_clients(max_number_of_clients){ } int Server::Start() { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); int socket_server; struct sockaddr_in localHost; memset(&localHost, 0, sizeof(localHost)); int new_socket; if( (socket_server= lwip_socket(AF_INET, SOCK_STREAM, 0))<0) { return -1; } localHost.sin_family = AF_INET; localHost.sin_port = htons(_port); //port localHost.sin_addr.s_addr = INADDR_ANY; //localhost address if (lwip_bind(socket_server, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) { return -1; } if (lwip_listen(socket_server,3)<0) { perror("listen"); exit(EXIT_FAILURE); } socklen_t newSockRemoteHostLen = sizeof(localHost); int tid; for(tid=0;tid<=_max_number_of_clients;tid++) { new_socket = lwip_accept(socket_server, (struct sockaddr*) &localHost, &newSockRemoteHostLen); if (new_socket < 0) { return -1; } osThreadCreate(osThread(Handle_client), (void *) new_socket); } return 1; }