Server.c 2.1 KB

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