Server.c 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* The server test program that accepts multiple TCP connections 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. * Run the client:
  11. * nc localhost 4000
  12. * [ type strings here, see them appear on the console ]
  13. */
  14. #include "api.h"
  15. #include "pal.h"
  16. #include "pal_debug.h"
  17. #define MAX_HANDLES 8
  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, sizeof(uri), "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[MAX_HANDLES];
  36. PAL_FLG events[MAX_HANDLES];
  37. PAL_FLG revents[MAX_HANDLES];
  38. int nhdls = 1;
  39. hdls[0] = srv;
  40. while (1) {
  41. for (int i = 0; i < MAX_HANDLES; i++) {
  42. events[i] = PAL_WAIT_READ | PAL_WAIT_WRITE;
  43. revents[i] = 0;
  44. }
  45. PAL_BOL polled = DkStreamsWaitEvents(nhdls, hdls, events, revents, NO_TIMEOUT);
  46. if (!polled)
  47. continue;
  48. for (int i = 0; i < MAX_HANDLES; i++) {
  49. if (revents[i]) {
  50. if (hdls[i] == srv) {
  51. /* event on server -- must be client connecting */
  52. PAL_HANDLE client_hdl = DkStreamWaitForClient(srv);
  53. if (!client_hdl)
  54. continue;
  55. if (nhdls >= MAX_HANDLES) {
  56. pal_printf("[ ] connection rejected\n");
  57. DkObjectClose(client_hdl);
  58. continue;
  59. }
  60. pal_printf("[%d] receive new connection\n", nhdls);
  61. hdls[nhdls++] = client_hdl;
  62. } else if (revents[i] & PAL_WAIT_READ) {
  63. /* event on client -- must read from client */
  64. int bytes = DkStreamRead(hdls[i], 0, 4096, buffer, NULL, 0);
  65. if (bytes == 0) {
  66. DkObjectClose(hdls[i]);
  67. for (int j = i + 1; j < nhdls; j++)
  68. hdls[j - 1] = hdls[j];
  69. nhdls--;
  70. continue;
  71. }
  72. int last_byte = bytes < 4096 ? bytes : 4095;
  73. ((char*)buffer)[last_byte] = 0;
  74. pal_printf("[%d] %s", i, (char*)buffer);
  75. }
  76. }
  77. }
  78. }
  79. return 0;
  80. }