socket_communicator_test.cc 2.05 KB
Newer Older
Chao Ma's avatar
Chao Ma committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*!
 *  Copyright (c) 2019 by Contributors
 * \file msg_queue.cc
 * \brief Message queue for DGL distributed training.
 */
#include <gtest/gtest.h>
#include <string.h>
#include <string>

#include "../src/graph/network/socket_communicator.h"

using std::string;
using dgl::network::SocketSender;
using dgl::network::SocketReceiver;

VoVAllen's avatar
VoVAllen committed
16
17
18
19
20
21
22
void start_client();
bool start_server();

#ifndef WIN32

#include <unistd.h>

Chao Ma's avatar
Chao Ma committed
23
TEST(SocketCommunicatorTest, SendAndRecv) {
Chao Ma's avatar
Chao Ma committed
24
25
26
  std::thread client_thread(start_client);
  start_server();
  client_thread.join();
VoVAllen's avatar
VoVAllen committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
}

#else   // WIN32

#include <windows.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

void sleep(int seconds) {
  Sleep(seconds * 1000);
}

DWORD WINAPI _ClientThreadFunc(LPVOID param) {
  start_client();
  return 0;
}

DWORD WINAPI _ServerThreadFunc(LPVOID param) {
  return start_server() ? 1 : 0;
}

TEST(SocketCommunicatorTest, SendAndRecv) {
  HANDLE hThreads[2];
  WSADATA wsaData;
  DWORD retcode, exitcode;

  ASSERT_EQ(::WSAStartup(MAKEWORD(2, 2), &wsaData), 0);

  hThreads[0] = ::CreateThread(NULL, 0, _ClientThreadFunc, NULL, 0, NULL);  // client
  ASSERT_TRUE(hThreads[0] != NULL);
  hThreads[1] = ::CreateThread(NULL, 0, _ServerThreadFunc, NULL, 0, NULL);  // server
  ASSERT_TRUE(hThreads[1] != NULL);

  retcode = ::WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
  EXPECT_TRUE((retcode <= WAIT_OBJECT_0 + 1) && (retcode >= WAIT_OBJECT_0));

  EXPECT_EQ(::GetExitCodeThread(hThreads[1], &exitcode), TRUE);
  EXPECT_EQ(exitcode, 1);

  EXPECT_EQ(::CloseHandle(hThreads[0]), TRUE);
  EXPECT_EQ(::CloseHandle(hThreads[1]), TRUE);

  ::WSACleanup();
}

#endif  // WIN32

void start_client() {
Chao Ma's avatar
Chao Ma committed
76
  const char * msg = "123456789";
VoVAllen's avatar
VoVAllen committed
77
78
79
80
  sleep(1);
  SocketSender sender;
  sender.AddReceiver("127.0.0.1", 2049, 0);
  sender.Connect();
Chao Ma's avatar
Chao Ma committed
81
  sender.Send(msg, 9, 0);
VoVAllen's avatar
VoVAllen committed
82
83
84
85
86
87
88
  sender.Finalize();
}

bool start_server() {
  char serbuff[10];
  memset(serbuff, '\0', 10);
  SocketReceiver receiver;
Chao Ma's avatar
Chao Ma committed
89
90
  receiver.Wait("127.0.0.1", 2049, 1, 500 * 1024);
  receiver.Recv(serbuff, 9);
VoVAllen's avatar
VoVAllen committed
91
  receiver.Finalize();
Chao Ma's avatar
Chao Ma committed
92
  return string("123456789") == string(serbuff);
VoVAllen's avatar
VoVAllen committed
93
}