Server.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* The server test program that accept multiple TCP connection at the same
  2. * time. A port number is taken as argument. If a port is locked up, try
  3. * another one.
  4. *
  5. * Run this progam with a simple tcp client, like netcat. For instance:
  6. *
  7. * Start the server:
  8. * ../src/libpal.so file:./Server.manifest 4000
  9. *
  10. *
  11. * Run the client:
  12. * nc localhost 4000
  13. * [ type strings here, see them appear on the console ]
  14. */
  15. #include "pal.h"
  16. #include "pal_debug.h"
  17. #include "api.h"
  18. int main (int argc, char ** argv)
  19. {
  20. if (argc < 2) {
  21. pal_printf("specify the port to open\n");
  22. return 0;
  23. }
  24. char uri[60];
  25. snprintf(uri, 60, "tcp.srv:127.0.0.1:%s", argv[1]);
  26. PAL_HANDLE srv = DkStreamOpen(uri, PAL_ACCESS_RDWR, 0,
  27. PAL_CREATE_TRY, 0);
  28. if (srv == NULL) {
  29. pal_printf("DkStreamOpen failed\n");
  30. return -1;
  31. }
  32. void * buffer = (void *) DkVirtualMemoryAlloc(NULL, 4096, 0,
  33. PAL_PROT_READ|PAL_PROT_WRITE);
  34. if (!buffer) {
  35. pal_printf("DkVirtualMemoryAlloc failed\n");
  36. return -1;
  37. }
  38. PAL_HANDLE hdls[8];
  39. int nhdls = 1, i;
  40. hdls[0] = srv;
  41. while(1) {
  42. PAL_HANDLE hdl = DkObjectsWaitAny(nhdls, hdls, NO_TIMEOUT);
  43. if (!hdl)
  44. continue;
  45. if (hdl == srv) {
  46. hdl = DkStreamWaitForClient(srv);
  47. if (!hdl)
  48. continue;
  49. if (nhdls >= 8) {
  50. pal_printf("[ ] connection rejected\n");
  51. DkObjectClose(hdl);
  52. continue;
  53. }
  54. pal_printf("[%d] receive new connection\n", nhdls);
  55. hdls[nhdls++] = hdl;
  56. continue;
  57. }
  58. int cnt = 0;
  59. for (i = 0 ; i < nhdls ; i++)
  60. if (hdls[i] == hdl)
  61. cnt = i;
  62. int bytes = DkStreamRead(hdl, 0, 4096, buffer, NULL, 0);
  63. if (bytes == 0) {
  64. DkObjectClose(hdls[cnt]);
  65. if (cnt != nhdls - 1)
  66. hdls[cnt] = hdls[nhdls - 1];
  67. nhdls--;
  68. continue;
  69. }
  70. ((char *) buffer)[bytes] = 0;
  71. pal_printf("[%d] %s", cnt, (char *) buffer);
  72. }
  73. return 0;
  74. }