Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,13 @@ ifeq ($(WITH_EVPP), yes)
endif
ifeq ($(WITH_HTTP), yes)
$(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Ihttp -o bin/websocket_parser_test unittest/websocket_parser_test.cpp -Llib -lhv -pthread
ifeq ($(WITH_EVPP), yes)
ifeq ($(WITH_HTTP_CLIENT), yes)
ifeq ($(WITH_HTTP_SERVER), yes)
$(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -Ihttp -Ihttp/client -Ihttp/server -o bin/websocket_client_close_test unittest/websocket_client_close_test.cpp -Llib -lhv -pthread
endif
endif
endif
endif
ifeq ($(WITH_EVPP), yes)
ifeq ($(WITH_REDIS), yes)
Expand Down
11 changes: 11 additions & 0 deletions docs/cn/WebSocketClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ class WebSocketClient {
std::function<void()> onopen;
// 关闭回调
std::function<void()> onclose;
// 在 onclose 中查询本次关闭状态
int getCloseCode() const;
// 消息回调
std::function<void(const std::string& msg)> onmessage;

Expand All @@ -34,4 +36,13 @@ class WebSocketClient {

```

在 `onclose()` 中调用 `getCloseCode()` 可区分以下情况。每次新连接的 `onopen()` 中,初始值都是 `NoCloseFrame`。

| 返回值 | 含义 |
| --- | --- |
| 非负整数 | 对端 CLOSE 帧携带的 16 位状态码,例如 `1000` 或应用自定义的 `4000` |
| `WebSocketClient::CloseCode::NoCloseStatus` | 已收到对端 CLOSE 帧,负载中没有完整的状态码 |
| `WebSocketClient::CloseCode::LocalClose` | 应用主动关闭客户端,关闭前未收到对端 CLOSE 帧 |
| `WebSocketClient::CloseCode::NoCloseFrame` | 连接中断或连接尝试失败,未收到对端 CLOSE 帧 |

测试代码见 [examples/websocket_client_test.cpp](../../examples/websocket_client_test.cpp)
14 changes: 14 additions & 0 deletions http/WebSocketChannel.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef HV_WEBSOCKET_CHANNEL_H_
#define HV_WEBSOCKET_CHANNEL_H_

#include <atomic>
#include <mutex>

#include "Channel.h"
Expand All @@ -12,6 +13,12 @@ namespace hv {

class HV_EXPORT WebSocketChannel : public SocketChannel {
public:
enum CloseCode {
NoCloseFrame = -1, // no peer CLOSE received
NoCloseStatus = -2, // peer CLOSE without a complete status code
LocalClose = -3, // application closed the client
};

ws_session_type type;
WebSocketChannel(hio_t* io, ws_session_type type = WS_CLIENT)
: SocketChannel(io)
Expand All @@ -35,6 +42,11 @@ class HV_EXPORT WebSocketChannel : public SocketChannel {
int sendPong();

int close() {
if (type == WS_CLIENT && isOpened()) {
// A write callback can request a local close while echoing a peer CLOSE.
int expected = NoCloseFrame;
close_code_.compare_exchange_strong(expected, LocalClose);
}
return SocketChannel::close(type == WS_SERVER);
}

Expand All @@ -44,6 +56,8 @@ class HV_EXPORT WebSocketChannel : public SocketChannel {
public:
enum ws_opcode opcode;
private:
friend class WebSocketClient;
std::atomic<int> close_code_{NoCloseFrame};
Buffer sendbuf_;
std::mutex mutex_;
};
Expand Down
29 changes: 22 additions & 7 deletions http/client/WebSocketClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,11 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
http_parser_->InitResponse(http_resp_.get());
} else {
state = WS_CLOSED;
// A later DNS failure can reuse this channel. Clear it after the
// notification even if the callback replaced the client's channel.
WebSocketChannelPtr closed = channel;
if (onclose) onclose();
closed->close_code_ = CloseCode::NoCloseFrame;
}
};
onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) {
Expand All @@ -111,7 +115,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
int nparse = http_parser_->FeedRecvData(data, size);
if (nparse != size && http_parser_->GetError()) {
hloge("http parse error!");
channel->close();
channel->SocketChannel::close();
return;
}
data += nparse;
Expand All @@ -134,7 +138,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
}
}
hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code);
channel->close();
channel->SocketChannel::close();
return;
}
std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY);
Expand All @@ -143,18 +147,29 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT);
if (strcmp(ws_accept, ws_accept2.c_str()) != 0) {
hloge("Sec-WebSocket-Accept not match!");
channel->close();
channel->SocketChannel::close();
return;
}
ws_parser_ = std::make_shared<WebSocketParser>();
// websocket_onmessage
ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
ws_parser_->onMessage = [this, channel](int opcode, const std::string& msg) {
channel->opcode = (enum ws_opcode)opcode;
switch (opcode) {
case WS_OPCODE_CLOSE:
{
// An earlier message in the same read may have closed the channel.
if (!channel->isConnected()) break;
uint16_t code;
if (msg.size() >= sizeof(code)) {
memcpy(&code, msg.data(), sizeof(code));
channel->close_code_ = ntohs(code);
} else {
channel->close_code_ = CloseCode::NoCloseStatus;
}
channel->send(msg, WS_OPCODE_CLOSE);
channel->close();
channel->SocketChannel::close();
break;
}
case WS_OPCODE_PING:
{
// printf("recv ping\n");
Expand Down Expand Up @@ -183,7 +198,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
if (channel == NULL) return;
if (ping_cnt++ == 3) {
hloge("websocket no pong!");
channel->close();
channel->SocketChannel::close();
return;
}
// printf("send ping\n");
Expand All @@ -197,7 +212,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
int nparse = ws_parser_->FeedRecvData(data, size);
if (nparse != size) {
hloge("websocket parse error!");
channel->close();
channel->SocketChannel::close();
return;
}
}
Expand Down
4 changes: 4 additions & 0 deletions http/client/WebSocketClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class HV_EXPORT WebSocketClient : public TcpClientTmpl<WebSocketChannel> {
// PATCH: onmessage not given opcode
enum ws_opcode opcode() { return channel ? channel->opcode : WS_OPCODE_CLOSE; }

using CloseCode = WebSocketChannel::CloseCode;
// Read in onclose. A nonnegative value is the status code sent by the peer.
int getCloseCode() const { return channel ? channel->close_code_.load() : CloseCode::NoCloseFrame; }

WebSocketClient(EventLoopPtr loop = NULL);
virtual ~WebSocketClient();

Expand Down
3 changes: 3 additions & 0 deletions scripts/unittest.sh
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ bin/http_router_test
if [ -x bin/websocket_parser_test ]; then
bin/websocket_parser_test || exit $?
fi
if [ -x bin/websocket_client_close_test ]; then
bin/websocket_client_close_test || exit $?
fi
if [ -x bin/tlv_test ]; then
bin/tlv_test
fi
Expand Down
6 changes: 6 additions & 0 deletions unittest/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ add_executable(websocket_parser_test websocket_parser_test.cpp)
target_include_directories(websocket_parser_test PRIVATE .. ../base ../http)
target_link_libraries(websocket_parser_test ${HV_LIBRARIES})
set(HTTP_UNITTEST_TARGETS websocket_parser_test)
if(WITH_EVPP AND WITH_HTTP_CLIENT AND WITH_HTTP_SERVER)
add_executable(websocket_client_close_test websocket_client_close_test.cpp)
target_include_directories(websocket_client_close_test PRIVATE .. ../base ../ssl ../event ../cpputil ../evpp ../http ../http/client ../http/server)
target_link_libraries(websocket_client_close_test ${HV_LIBRARIES})
list(APPEND HTTP_UNITTEST_TARGETS websocket_client_close_test)
endif()
endif()

if(WITH_LUA)
Expand Down
108 changes: 108 additions & 0 deletions unittest/websocket_client_close_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#include <cstdio>
#include <cstdlib>
#include <string>

#include "WebSocketClient.h"
#include "WebSocketServer.h"

using namespace hv;

#define CHECK(expr) do { if (!(expr)) { \
std::fprintf(stderr, "line %d: %s failed\n", __LINE__, #expr); \
std::exit(1); \
} } while (0)

int main() {
WebSocketService peer;
peer.onmessage = [](const WebSocketChannelPtr& ch, const std::string& msg) {
ch->send("ready");
if (msg == "local") {
ch->send(std::string("\x03\xe8"), WS_OPCODE_CLOSE);
} else if (msg == "coded") {
// Application code 4000 in network byte order, followed by a reason.
ch->send(std::string("\x0f\xa0maintenance"), WS_OPCODE_CLOSE);
} else if (msg == "empty") {
ch->send(std::string(), WS_OPCODE_CLOSE);
} else {
CHECK(msg == "drop");
ch->close();
}
};
WebSocketServer server(&peer);
server.setHost("127.0.0.1");
server.setPort(0);
CHECK(server.start() == 0);
std::string url = "ws://127.0.0.1:" + std::to_string(server.port) + "/";

struct {
const char* command;
int code;
} cases[] = {
{"local", WebSocketClient::CloseCode::LocalClose},
{"drop", WebSocketClient::CloseCode::NoCloseFrame},
{"coded", 4000},
{"empty", WebSocketClient::CloseCode::NoCloseStatus},
{"coded", 4000},
};
const size_t count = sizeof(cases) / sizeof(cases[0]);
size_t closed = 0;
std::string events;
char readbuf[64]; // valid until the parser finishes, including after close()
EventLoopPtr loop = std::make_shared<EventLoop>();
WebSocketClient client(loop);
reconn_setting_t reconn;
reconn_setting_init(&reconn);
reconn.min_delay = reconn.max_delay = 10;
auto connect = [&]() {
client.setReconnect(&reconn);
CHECK(client.open(url.c_str()) == 0);
};
client.onopen = [&]() {
CHECK(closed < count);
CHECK(client.getCloseCode() == WebSocketClient::CloseCode::NoCloseFrame);
events += "open ";
if (closed == 0) {
// Deliver TEXT and CLOSE in one parser call. The TEXT callback
// closes the client before the parser reaches the peer's CLOSE.
int bytes = ws_calc_frame_size(5) + ws_calc_frame_size(2);
client.channel->setReadBuf(readbuf, sizeof(readbuf));
CHECK(client.channel->readBytes(bytes) >= 0);
}
client.send(cases[closed].command);
};
client.onmessage = [&](const std::string& msg) {
CHECK(closed < count && msg == "ready");
events += "message ";
if (closed == 0) client.close();
};
client.onclose = [&]() {
CHECK(!client.isConnected());
if (closed == count) {
// The server stopped after the last coded CLOSE. The retry failed
// before onopen, so it must not report the previous peer's code.
CHECK(events.empty());
CHECK(client.getCloseCode() == WebSocketClient::CloseCode::NoCloseFrame);
client.setReconnect(NULL);
loop->stop();
return;
}
CHECK(events == "open message ");
CHECK(client.getCloseCode() == cases[closed].code);
events.clear();
++closed;
if (closed == 1) {
// Local close disables automatic reconnect. Reopen the same client.
loop->queueInLoop(connect);
} else if (closed == count) {
server.stop();
}
};

loop->queueInLoop(connect);
loop->setTimeout(5000, [](TimerID) {
std::fprintf(stderr, "timed out waiting for WebSocket callbacks\n");
std::exit(1);
});
loop->run();
return 0;
}