-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
47 lines (39 loc) · 1.28 KB
/
Copy pathclient.cpp
File metadata and controls
47 lines (39 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/base/Logging.h>
using namespace muduo;
using namespace muduo::net;
class Myclient{
public:
Myclient(EventLoop* loop, const InetAddress& serverAddr, const string& nameArg)
:loop_(loop),client_(loop, serverAddr, nameArg){
client_.setConnectionCallback(std::bind(&Myclient::onConnection, this, std::placeholders::_1));
client_.setMessageCallback(std::bind(&Myclient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
void connect(){
client_.connect();
}
private:
EventLoop* loop_;
TcpClient client_;
void onConnection(const TcpConnectionPtr& conn) {
if (conn->connected()) {
LOG_INFO << "Connected to server: " << conn->peerAddress().toIpPort();
conn->send("Hello, Muduo!");
} else {
LOG_INFO << "Disconnected from server: " << conn->peerAddress().toIpPort();
}
}
void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) {
string msg(buf->retrieveAllAsString());
LOG_INFO << "Received " << msg.size() << " bytes from server: " << msg;
}
};
int main() {
EventLoop loop;
InetAddress serverAddr("127.0.0.1", 9877); // Server address
Myclient client(&loop, serverAddr, "SimpleClient");
client.connect();
loop.loop();
return 0;
}