Server.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. int main (int argc, char ** argv)
  20. {
  21. if (argc < 2) {
  22. pal_printf("specify the port to open\n");
  23. return 0;
  24. }
  25. char uri[60];
  26. pal_snprintf(uri, 60, "tcp.srv:127.0.0.1:%s", argv[1]);
  27. PAL_HANDLE srv = DkStreamOpen(uri, PAL_ACCESS_RDWR, 0,
  28. PAL_CREAT_TRY, 0);
  29. if (srv == NULL) {
  30. pal_printf("DkStreamOpen failed\n");
  31. return -1;
  32. }
  33. void * buffer = DkVirtualMemoryAlloc(NULL, 4096, 0,
  34. PAL_PROT_READ|PAL_PROT_WRITE);
  35. if (buffer == NULL) {
  36. pal_printf("DkVirtualMemoryAlloc failed\n");
  37. return -1;
  38. }
  39. PAL_HANDLE hdls[8];
  40. int nhdls = 1, i;
  41. hdls[0] = srv;
  42. while(1) {
  43. PAL_HANDLE hdl = DkObjectsWaitAny(nhdls, hdls, NO_TIMEOUT);
  44. if (!hdl)
  45. continue;
  46. if (hdl == srv) {
  47. hdl = DkStreamWaitForClient(srv);
  48. if (!hdl)
  49. continue;
  50. if (nhdls >= 8) {
  51. pal_printf("[ ] connection rejected\n");
  52. DkObjectClose(hdl);
  53. continue;
  54. }
  55. pal_printf("[%d] receive new connection\n", nhdls);
  56. hdls[nhdls++] = hdl;
  57. continue;
  58. }
  59. int cnt = 0;
  60. for (i = 0 ; i < nhdls ; i++)
  61. if (hdls[i] == hdl)
  62. cnt = i;
  63. int bytes = DkStreamRead(hdl, 0, 4096, buffer, NULL, 0);
  64. if (bytes == 0) {
  65. DkObjectClose(hdls[cnt]);
  66. if (cnt != nhdls - 1)
  67. hdls[cnt] = hdls[nhdls - 1];
  68. nhdls--;
  69. continue;
  70. }
  71. ((char *) buffer)[bytes] = 0;
  72. pal_printf("[%d] %s", cnt, (char *) buffer);
  73. }
  74. return 0;
  75. }