Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: ThreadServer Server_Multi_Client
Server.cpp
- Committer:
- lemniskata
- Date:
- 2013-06-29
- Revision:
- 4:c57a998796ae
- Parent:
- 1:e1db78d5ccc1
File content as of revision 4:c57a998796ae:
/* ** 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: Ivan Shindev ** Modified date: 06/29/2013 ** Version: ** Descriptions: Added functionality of running multiple thread instances of the same function ********************************************************************************************************/ #include "Server.h" #include "mbed.h" #include "Threads.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 { } } 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); ThreadList* my_threads=NULL; //List of all Initialized threads ThreadList* thread; //pointer to the last created ThreadList element int max=_max_number_of_clients; while(1) { new_socket = lwip_accept(socket_server, (struct sockaddr*) &localHost, &newSockRemoteHostLen); if (new_socket < 0) { } else { if(initThread(&my_threads,Handle_client,&thread,max)==0) { lwip_close(new_socket); } else { thread->id=osThreadCreate(thread->thread,(void *) new_socket); } } } }