Server.c 2.4 KB

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