Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "server.h"
- static int nrClients = 0;
- static sys_sem_t semaphore;
- static struct netconn *listener;
- void client (void *arg){
- struct netconn *session;
- struct netbuf * netBuf = netbuf_new ();
- int cl, rc;
- char buf[100];
- char message[] = "Message received\n";
- arg = arg;
- netconn_accept(listener, &session);
- cl = nrClients;
- nrClients++;
- printf("Connected: %i\n", cl);
- sys_sem_signal(&semaphore);
- while(1){
- rc = netconn_recv(session, &netBuf);
- if(rc != ERR_OK){
- fprintf(stderr, "Disconnected: %i\n", cl);
- nrClients--;
- netconn_disconnect(session);
- netconn_delete(session);
- return;
- }
- netbuf_copy(netBuf, (void **)&buf, 100);
- printf("Received from %i : %s", cl, buf);
- netconn_write(session, message, strlen(message), NETCONN_COPY);
- netbuf_delete(netBuf);
- }
- }
- void server(void *args){
- int rc;
- struct ip_addr listenaddr = { 0 };
- args = args;
- listener = netconn_new(NETCONN_TCP);
- rc = netconn_bind(listener, &listenaddr, PORT);
- VDIE(rc != ERR_OK, "netconn_bind");
- rc = netconn_listen(listener);
- VDIE(rc != ERR_OK, "netconn_listen");
- sys_sem_new(&semaphore, 0);
- while(1){
- /* Waiting for the listener semaphore to tell us a new connection is ready */
- sys_arch_sem_wait(&listener->acceptmbox->not_empty, 0);
- create_thread("client", client, NULL);
- fprintf(stderr, "Waiting for semaphore\n");
- /* Wait for the new thread to finish using the listener */
- sys_arch_sem_wait(&semaphore, 0);
- fprintf(stderr, "Semaphore ready\n");
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement