Skip to content

Commit 61489ac

Browse files
committed
rewrited the readme
1 parent c96d6cd commit 61489ac

File tree

1 file changed

+41
-16
lines changed

1 file changed

+41
-16
lines changed

README.md

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,60 @@
11

2-
C++实现的WebSocket协议,但采用的同步通信模型,不是异步的
2+
## websocket-cpp
33

4-
## 依赖项目
4+
WebSocket协议的C++实现,多线程同步模型 Simple && Lightweight
55

6-
* [tstream](https://github.com/luzhlon/tstream)
6+
## 文档
77

8-
## 服务端
8+
* Wiki: https://github.com/luzhlon/websocket-cpp/wiki
9+
10+
## 服务端示例
911

1012
```cpp
1113
#include "websocket.hpp"
14+
using namespace websocket;
15+
```
16+
17+
最简单的使用方法:
18+
19+
```cpp
20+
WebSocketServer<WebSocketHandler> server("127.0.0.1", 2048);
21+
auto handler = server.accept();
22+
// receive data
23+
cout << handler.recv().data() << endl;
24+
// send data
25+
handler.send(handler.data());
26+
// close the websocket connection
27+
handler.close();
28+
```
29+
30+
继承WebSocketHandler,重载onopen、onmessage、onclose等函数,调用WebSocketServer的run()函数,自动进行多线程处理
1231
13-
int main {
14-
tstream::server ser(5333);
15-
WebSocketHandler h = ser.accept();
16-
if (h) { // Open the connection successfully
32+
```cpp
33+
class MyHandler : public WebSocketHandler {
34+
public:
35+
static void onopen(MyHandler& h) {
36+
cout << "OPEN: " << h.getHost() << endl;
1737
cout << "GET " << h.getPath() << endl;
1838
cout << "Host: " << h.getHost() << endl;
1939
cout << "Sec-WebSocket-Key: " << h.getKey() << endl;
2040
cout << "Sec-WebSocket-Protocol: " << h.getSubProtocol() << endl;
21-
while (1) {
22-
if (h.recv())
23-
cout << h.data() << endl,
24-
h.send(h.data()); // send string data
25-
h.send(h.data(), true); // send binary data
26-
getchar();
27-
}
2841
}
42+
// Received a message
43+
static void onmessage(MyHandler& h) {
44+
cout << h.data() << endl;
45+
h.send(h.data()); // send a message to peer
46+
}
47+
static void onclose(MyHandler& h) {
48+
cout << "CLOSED" << endl;
49+
}
50+
};
51+
int main() {
52+
WebSocketServer<MyHandler> server("127.0.0.1", 2048);
53+
server.run();
2954
return 0;
3055
}
3156
```
3257

3358
## 客户端
3459

35-
未实现
60+
暂未实现

0 commit comments

Comments
 (0)