TCP Server that handles multiple client requests at the same time using multiple threads
Dependencies: EthernetInterface Server mbed-rtos mbed Threads
main.cpp
- Committer:
- lemniskata
- Date:
- 2013-06-11
- Revision:
- 0:724a1b7b59ca
- Child:
- 1:35d97f58d4d9
File content as of revision 0:724a1b7b59ca:
#include "mbed.h" #include "EthernetInterface.h" Serial pc(USBTX, USBRX); #define SERVER_PORT 1234 #define BUFFLEN 100 int bufsize=1024; //Size of the shared memory char *buffer; //This is the shared memory between the child threads void Handle_client(void const *socket_data) { int socket; socket = (int)socket_data; pc.printf("Socket connected #%d\n",socket); // pthread_mutex_lock (&mutex); pc.printf("Shared memory message is %s\n",buffer); lwip_recv(socket,buffer,bufsize,0); if (lwip_send(socket,buffer,strlen(buffer),0)!=strlen(buffer)) //send the content of the shared memory back to the socket { pc.printf("failed send\n"); } pc.printf("Message sent successfully to socket %d\n",socket); } int main (void) { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); pc.printf("IP Address is %s\n", eth.getIPAddress()); 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) { pc.printf("failed socket init\n"); return -1; } localHost.sin_family = AF_INET; localHost.sin_port = htons(SERVER_PORT); localHost.sin_addr.s_addr = INADDR_ANY; if (lwip_bind(socket_server, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) { pc.printf("failed socket bind init\n"); 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<=2;tid++) { new_socket = lwip_accept(socket_server, (struct sockaddr*) &localHost, &newSockRemoteHostLen); if (new_socket < 0) { pc.printf("failed socket accept\n"); return -1; } Thread t(Handle_client, (void *) new_socket); } }