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:
- 1:35d97f58d4d9
- Parent:
- 0:724a1b7b59ca
- Child:
- 2:fe6ad47cd3eb
File content as of revision 1:35d97f58d4d9:
#include "mbed.h" #include "EthernetInterface.h" #define SERVER_PORT 7 #define BUFFLEN 100 int bufsize=1024; //Size of the shared memory char *buffer; //This is the shared memory between the child threads void Debug(void const *data) { TCPSocketServer server; server.bind(SERVER_PORT); server.listen(); while (true) { printf("\nWait for new connection...\n"); TCPSocketConnection client; server.accept(client); client.set_blocking(false, 1500); // Timeout after (1.5)s printf("Connection from: %s\n", client.get_address()); char buffer[256]; while (true) { int n = client.receive(buffer, sizeof(buffer)); if (n <= 0) break; client.send_all(buffer, n); if (n <= 0) break; } client.close(); } } void Handle_client(void const *socket_data) { int socket; socket = (int)socket_data; //pc.printf("Socket connected #%d\n",socket); //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(); Thread t1(Debug, (void *) 1); while(1) { } // 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); }*/ }