1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/curvecp/test_server.h"
9 #include "base/logging.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/ip_endpoint.h"
12 #include "net/base/net_errors.h"
13 #include "net/base/net_util.h"
14 #include "net/curvecp/curvecp_server_socket.h"
18 TestServer::TestServer()
23 TestServer::~TestServer() {
30 bool TestServer::Start(int port
) {
31 IPAddressNumber ip_number
;
32 std::string
ip_str("0.0.0.0");
33 if (!ParseIPLiteralToNumber(ip_str
, &ip_number
)) {
34 LOG(ERROR
) << "Bad IP Address";
37 IPEndPoint
bind_address(ip_number
, port
);
40 socket_
= new CurveCPServerSocket(NULL
, NetLog::Source());
41 int rv
= socket_
->Listen(bind_address
, this);
42 if (rv
< ERR_IO_PENDING
) {
43 LOG(ERROR
) << "Listen on port " << port
<< " failed: " << rv
;
49 void TestServer::OnAccept(CurveCPServerSocket
* new_socket
) {
51 LOG(ERROR
) << "Accepted socket! Starting Echo Server";
52 EchoServer
* new_server
= new EchoServer();
53 new_server
->Start(new_socket
);
56 EchoServer::EchoServer()
61 EchoServer::~EchoServer() {
64 void EchoServer::Start(CurveCPServerSocket
* socket
) {
69 // Note: |this| could be deleted here.
72 void EchoServer::OnReadComplete(int result
) {
73 LOG(INFO
) << "Read complete: " << result
;
79 bytes_received_
+= result
;
80 LOG(INFO
) << "Server received " << result
<< "(" << bytes_received_
<< ")";
82 if (!received_stream_
.VerifyBytes(read_buffer_
->data(), result
)) {
83 LOG(ERROR
) << "Server Received corrupt receive data!";
88 // Echo the read data back here.
89 DCHECK(!write_buffer_
.get());
90 write_buffer_
= new DrainableIOBuffer(read_buffer_
, result
);
91 int rv
= socket_
->Write(write_buffer_
, result
,
92 base::Bind(&EchoServer::OnWriteComplete
,
93 base::Unretained(this)));
94 if (rv
== ERR_IO_PENDING
)
99 void EchoServer::OnWriteComplete(int result
) {
105 write_buffer_
->DidConsume(result
);
106 while (write_buffer_
->BytesRemaining()) {
107 int rv
= socket_
->Write(write_buffer_
,
108 write_buffer_
->BytesRemaining(),
109 base::Bind(&EchoServer::OnWriteComplete
,
110 base::Unretained(this)));
111 if (rv
== ERR_IO_PENDING
)
116 // Now we can read more data.
117 write_buffer_
= NULL
;
118 // read_buffer_ = NULL;
122 void EchoServer::ReadData() {
123 DCHECK(!read_buffer_
.get());
124 read_buffer_
= new IOBuffer(kMaxMessage
);
128 rv
= socket_
->Read(read_buffer_
, kMaxMessage
,
129 base::Bind(&EchoServer::OnReadComplete
,
130 base::Unretained(this)));
131 if (rv
== ERR_IO_PENDING
)
133 OnReadComplete(rv
); // Complete the read manually