SocketTest.cpp 6.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

X
Xin Pan 已提交
15
#include "paddle/legacy/utils/Util.h"
Z
zhangjinchao01 已提交
16 17 18

#include <netdb.h>
#include <netinet/in.h>
Y
Yu Yang 已提交
19 20 21
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
Z
zhangjinchao01 已提交
22 23 24

#include <thread>

X
Xin Pan 已提交
25
#include "paddle/legacy/math/Vector.h"
X
Xin Pan 已提交
26
#include "paddle/legacy/utils/Logging.h"
Z
zhangjinchao01 已提交
27 28 29 30 31 32

struct MessageHeader {
  int64_t dataLength;
};

class Thread {
W
Wu Yi 已提交
33
 public:
Z
zhangjinchao01 已提交
34 35 36 37
  void start();
  virtual void run() = 0;
  virtual ~Thread() {}

W
Wu Yi 已提交
38
 protected:
Z
zhangjinchao01 已提交
39 40 41 42 43 44 45 46
  std::unique_ptr<std::thread> thread_;
};

void Thread::start() {
  thread_.reset(new std::thread([this]() { this->run(); }));
}

class SocketChannel {
W
Wu Yi 已提交
47
 public:
Z
zhangjinchao01 已提交
48 49 50 51 52
  explicit SocketChannel(int socket) : socket_(socket) {}
  int getSocketFd() const { return socket_; }
  uint64_t readAll(void* buf, size_t size);
  uint64_t writeAll(const void* buf, size_t size);

W
Wu Yi 已提交
53
 protected:
Z
zhangjinchao01 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  int socket_;
};

uint64_t SocketChannel::readAll(void* buf, size_t size) {
  uint64_t total = 0;
  while (total < size) {
    int64_t len = read(socket_, (char*)buf + total, size - total);
    if (len <= 0) {
      return total;
    }
    total += len;
  }
  return total;
}

uint64_t SocketChannel::writeAll(const void* buf, size_t size) {
  uint64_t total = 0;
  while (total < size) {
    int64_t len = write(socket_, (const char*)buf + total, size - total);
    if (len <= 0) {
      return total;
    }
    total += len;
  }
  return total;
}

class SocketWorker : public Thread {
W
Wu Yi 已提交
82
 public:
Z
zhangjinchao01 已提交
83 84 85 86 87 88 89 90
  explicit SocketWorker(int socket) : channel_(socket) {}
  virtual void run();

  // read n bytes.
  int64_t readAll(char* buf, size_t n);

  // write n bytes

W
Wu Yi 已提交
91
 protected:
Z
zhangjinchao01 已提交
92 93 94 95 96
  SocketChannel channel_;
  std::string buffer_;
};

class SocketServer : public Thread {
W
Wu Yi 已提交
97
 public:
Z
zhangjinchao01 已提交
98 99 100 101 102
  explicit SocketServer(int port)
      : port_(port), socket_(0), maxPendingConnections_(100) {}

  virtual void run();

W
Wu Yi 已提交
103
 protected:
Z
zhangjinchao01 已提交
104 105 106 107 108 109 110 111 112 113 114 115
  int port_;
  int socket_;
  int maxPendingConnections_;
};

void SocketServer::run() {
  int newsockfd;
  socklen_t clilen;
  struct sockaddr_in serv_addr, cli_addr;

  /* First call to socket() function */
  socket_ = socket(AF_INET, SOCK_STREAM, 0);
Y
Yu Yang 已提交
116
  CHECK(socket_ >= 0) << "ERROR opening socket";
Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124

  /* Initialize socket structure */
  bzero((char*)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(port_);

  /* Now bind the host address using bind() call.*/
Y
Yu Yang 已提交
125
  CHECK(bind(socket_, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) >= 0)
Z
zhangjinchao01 已提交
126 127 128 129 130 131 132 133 134 135 136
      << "ERROR on binding";

  /* Now start listening for the clients, here process will
   * go in sleep mode and will wait for the incoming connection
   */
  listen(socket_, maxPendingConnections_);
  clilen = sizeof(cli_addr);

  while (true) {
    /* Accept actual connection from the client */
    newsockfd = accept(socket_, (struct sockaddr*)&cli_addr, &clilen);
Y
Yu Yang 已提交
137
    CHECK(newsockfd >= 0) << "ERROR on accept";
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146 147 148

    SocketWorker* worker = new SocketWorker(newsockfd);
    worker->start();
  }
}

void SocketWorker::run() {
  MessageHeader header;

  while (true) {
    int64_t n = channel_.readAll(&header, sizeof(header));
Y
Yu Yang 已提交
149
    CHECK(n == sizeof(header)) << "ERROR reading from socket";
Z
zhangjinchao01 已提交
150 151 152

    buffer_.resize(header.dataLength);
    n = channel_.readAll(&buffer_[0], header.dataLength);
Y
Yu Yang 已提交
153
    CHECK(n == header.dataLength) << "ERROR reading from socket";
Z
zhangjinchao01 已提交
154 155 156

    /* Write a response to the client */
    n = channel_.writeAll(&header, sizeof(header));
Y
Yu Yang 已提交
157
    CHECK(n == sizeof(header)) << "ERROR reading from socket";
Z
zhangjinchao01 已提交
158
    n = channel_.writeAll(buffer_.data(), buffer_.size());
Y
Yu Yang 已提交
159
    CHECK(n == header.dataLength) << "ERROR writing to socket";
Z
zhangjinchao01 已提交
160 161 162 163
  }
}

class SocketClient {
W
Wu Yi 已提交
164
 public:
Z
zhangjinchao01 已提交
165 166 167
  SocketClient(const std::string& serverAddr, int serverPort);
  SocketChannel* getChannel() const { return channel_.get(); }

W
Wu Yi 已提交
168
 protected:
Z
zhangjinchao01 已提交
169 170 171 172 173 174 175 176 177 178 179
  std::unique_ptr<SocketChannel> channel_;
};

SocketClient::SocketClient(const std::string& serverAddr, int serverPort) {
  struct sockaddr_in serv_addr;
  struct hostent* server;

  // char buffer[256];

  /* Create a socket point */
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
Y
Yu Yang 已提交
180
  CHECK(sockfd >= 0) << "ERROR opening socket";
Z
zhangjinchao01 已提交
181
  server = gethostbyname(serverAddr.c_str());
Y
Yu Yang 已提交
182
  CHECK(server) << "ERROR, no such host: " << serverAddr;
Z
zhangjinchao01 已提交
183 184 185

  bzero((char*)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
186 187
  bcopy((char*)server->h_addr,
        (char*)&serv_addr.sin_addr.s_addr,
Z
zhangjinchao01 已提交
188 189 190 191
        server->h_length);
  serv_addr.sin_port = htons(serverPort);

  /* Now connect to the server */
Y
Yu Yang 已提交
192
  CHECK(connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) >= 0)
Z
zhangjinchao01 已提交
193 194 195 196 197
      << "ERROR connecting";

  channel_.reset(new SocketChannel(sockfd));
}

198 199 200
DEFINE_string(server_addr, "127.0.0.1", "Server address");
DEFINE_int64(dim, 10000000, "Data size");
DEFINE_int32(loop_time, 100000, "test loop time");
Z
zhangjinchao01 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

using namespace paddle;  // NOLINT

int main(int argc, char** argv) {
  paddle::initMain(argc, argv);
  SocketServer server(FLAGS_port);
  server.start();
  sleep(1);

  SocketClient client(FLAGS_server_addr, FLAGS_port);

  SocketChannel* channel = client.getChannel();

  MessageHeader header;

  uint64_t dataSize = FLAGS_dim * sizeof(real);

218
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  GpuVector gpuParam(FLAGS_dim);
  GpuVector gpuGrad(FLAGS_dim);
#else
  CpuVector gpuParam(FLAGS_dim);
  CpuVector gpuGrad(FLAGS_dim);
#endif
  CpuVector cpuParam(FLAGS_dim);
  CpuVector cpuGrad(FLAGS_dim);

  gpuParam.rand();
  gpuGrad.rand();
  cpuParam.rand();
  cpuGrad.rand();

  for (int i = 0; i < FLAGS_loop_time; ++i) {
    cpuGrad.copyFrom(gpuGrad);

    header.dataLength = dataSize;
Y
Yu Yang 已提交
237
    CHECK(channel->writeAll(&header, sizeof(header)) == sizeof(header))
Z
zhangjinchao01 已提交
238 239
        << "Client write header error";

Y
Yu Yang 已提交
240
    CHECK(channel->writeAll(cpuGrad.getData(), dataSize) == dataSize)
Z
zhangjinchao01 已提交
241 242 243
        << "Client write data error";

    /* Now read server response */
Y
Yu Yang 已提交
244
    CHECK(channel->readAll(&header, sizeof(header)) == sizeof(header))
Z
zhangjinchao01 已提交
245 246 247
        << "Client read header error";

    CHECK_EQ((uint64_t)header.dataLength, dataSize);
Y
Yu Yang 已提交
248
    CHECK(channel->readAll(cpuParam.getData(), dataSize) == dataSize)
Z
zhangjinchao01 已提交
249 250 251 252 253 254 255 256
        << "Client read data error";

    gpuParam.copyFrom(cpuParam);

    LOG_EVERY_N(INFO, 100) << "i=" << i;
  }
  exit(0);
}