Advertisement
Guest User

Untitled

a guest
Sep 20th, 2015
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include "server.h"
  2.  
  3. static int nrClients = 0;
  4. static sys_sem_t semaphore;
  5. static struct netconn *listener;
  6.  
  7. void client (void *arg){
  8.  
  9.     struct netconn *session;
  10.     struct netbuf * netBuf = netbuf_new ();
  11.     int cl, rc;
  12.     char buf[100];
  13.     char message[] = "Message received\n";
  14.  
  15.     arg = arg;
  16.     netconn_accept(listener, &session);
  17.  
  18.     cl = nrClients;
  19.     nrClients++;
  20.     printf("Connected: %i\n", cl);
  21.     sys_sem_signal(&semaphore);
  22.  
  23.     while(1){
  24.         rc = netconn_recv(session, &netBuf);
  25.         if(rc != ERR_OK){
  26.             fprintf(stderr, "Disconnected: %i\n", cl);
  27.             nrClients--;
  28.             netconn_disconnect(session);
  29.             netconn_delete(session);
  30.             return;
  31.         }
  32.  
  33.         netbuf_copy(netBuf, (void **)&buf, 100);
  34.         printf("Received from %i : %s", cl, buf);
  35.  
  36.         netconn_write(session, message, strlen(message), NETCONN_COPY);
  37.         netbuf_delete(netBuf);
  38.     }
  39. }
  40.  
  41. void server(void *args){
  42.  
  43.     int rc;
  44.     struct ip_addr listenaddr = { 0 };
  45.  
  46.     args = args;
  47.     listener = netconn_new(NETCONN_TCP);
  48.  
  49.     rc = netconn_bind(listener, &listenaddr, PORT);
  50.     VDIE(rc != ERR_OK, "netconn_bind");
  51.  
  52.     rc = netconn_listen(listener);
  53.     VDIE(rc != ERR_OK, "netconn_listen");
  54.  
  55.     sys_sem_new(&semaphore, 0);
  56.  
  57.     while(1){
  58.         /* Waiting for the listener semaphore to tell us a new connection is ready */
  59.         sys_arch_sem_wait(&listener->acceptmbox->not_empty, 0);
  60.         create_thread("client", client, NULL);
  61.  
  62.         fprintf(stderr, "Waiting for semaphore\n");
  63.         /* Wait for the new thread to finish using the listener */
  64.         sys_arch_sem_wait(&semaphore, 0);
  65.         fprintf(stderr, "Semaphore ready\n");
  66.  
  67.     }
  68.  
  69.     return;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement