Changeset 371ce29 in network-game for server


Ignore:
Timestamp:
Nov 28, 2012, 3:38:24 PM (12 years ago)
Author:
dportnoy <dmp1488@…>
Branches:
master
Children:
439f7bc
Parents:
59061f6
Message:

The server now uses nonblocking sockets and sleep to free up cpu usage

File:
1 edited

Legend:

Unmodified
Added
Removed
  • server/server.cpp

    r59061f6 r371ce29  
    22
    33#include <cstdlib>
     4#include <cstdio>
    45#include <unistd.h>
    56#include <string>
    6 #include <netdb.h>
    7 #include <cstdio>
    87#include <iostream>
    98#include <vector>
    109#include <algorithm>
    1110
     11#include <fcntl.h>
     12#include <assert.h>
     13
    1214#include <sys/socket.h>
     15#include <netdb.h>
    1316#include <netinet/in.h>
    1417#include <arpa/inet.h>
     
    7780}
    7881
     82void set_nonblock(int sock)
     83{
     84    int flags;
     85    flags = fcntl(sock, F_GETFL,0);
     86    assert(flags != -1);
     87    fcntl(sock, F_SETFL, flags | O_NONBLOCK);
     88}
     89
    7990int main(int argc, char *argv[])
    8091{
     
    8697
    8798   srand(time(NULL));
    88    int num = (rand() % 1000) + 1;
     99   int num = 500;
     100   //int num = (rand() % 0) + 1;
    89101
    90102   cout << "num: " << num << endl;
     
    99111   }
    100112
     113   /*
    101114   DataAccess da;
    102115
     
    116129   da.printPlayers();
    117130   cout << endl;
     131   */
    118132   
    119    sock=socket(AF_INET, SOCK_DGRAM, 0);
     133   sock = socket(AF_INET, SOCK_DGRAM, 0);
    120134   if (sock < 0) error("Opening socket");
    121135   length = sizeof(server);
     
    127141      error("binding");
    128142
     143   set_nonblock(sock);
     144
    129145   while (true) {
    130       // if n == 0, means the client disconnected. may want to check this
     146
     147      usleep(5000);
     148
    131149      n = receiveMessage(&clientMsg, sock, &from);
    132       if (n < 0)
    133          error("recieveMessage");
    134 
    135       processMessage(clientMsg, from, vctPlayers, num, serverMsg);
    136 
    137       cout << "msg: " << serverMsg.buffer << endl;
    138 
    139       n = sendMessage(&serverMsg, sock, &from);
    140       if (n  < 0)
    141          error("sendMessage");
    142    }
     150
     151      if (n >= 0) {
     152         cout << "Got a message" << endl;
     153
     154         processMessage(clientMsg, from, vctPlayers, num, serverMsg);
     155
     156         cout << "msg: " << serverMsg.buffer << endl;
     157
     158         n = sendMessage(&serverMsg, sock, &from);
     159         if (n  < 0)
     160            error("sendMessage");
     161      }
     162
     163   }
     164
    143165   return 0;
    144166}
Note: See TracChangeset for help on using the changeset viewer.