TcpClient/Reactor 框架
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
#include "c_TcpClient.h"
|
||||
#include "c_TcpClientPollReactor.h"
|
||||
#include "c_SocketUtil.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
static bool OnConnect(c_TcpClient_t* client, void* args) {
|
||||
char ip[128];
|
||||
char port[32];
|
||||
c_SocketUtil_GetNameInfoForSocket(client->sock, ip, sizeof(ip), port, sizeof(port));
|
||||
printf("[CONN] %s:%s\n", ip, port);
|
||||
c_TcpClient_Send(client, "Hello", 5, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool OnData(c_TcpClient_t* client, void* args) {
|
||||
char ip[128];
|
||||
char port[32];
|
||||
c_SocketUtil_GetNameInfoForSocket(client->sock, ip, sizeof(ip), port, sizeof(port));
|
||||
printf("[DATA] %s:%s\n", ip, port);
|
||||
char buffer[1024]={0};
|
||||
c_size_t recv_bytes = 0;
|
||||
c_TcpClient_Recv(client, buffer, sizeof(buffer), &recv_bytes);
|
||||
printf("%.*s\n", (int)recv_bytes, buffer);
|
||||
return false;
|
||||
}
|
||||
|
||||
static void OnDisconnect(c_TcpClient_t* client, void* args) {
|
||||
char ip[128];
|
||||
char port[32];
|
||||
c_SocketUtil_GetNameInfoForSocket(client->sock, ip, sizeof(ip), port, sizeof(port));
|
||||
printf("[CLOSE] %s:%s\n", ip, port);
|
||||
}
|
||||
|
||||
static void OnError(c_TcpClient_t* client, c_err_t err, void* args) {
|
||||
|
||||
if (c_Socket_IsValid(client->sock)) {
|
||||
char ip[128];
|
||||
char port[32];
|
||||
c_SocketUtil_GetNameInfoForSocket(client->sock, ip, sizeof(ip), port, sizeof(port));
|
||||
printf("[ERROR] %s:%s code:%d\n", ip, port, err);
|
||||
}else {
|
||||
printf("[ERROR] code:%d\n", err);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main(int argc, char** argv){
|
||||
c_Socket_Init();
|
||||
|
||||
c_TcpClient_t client=C_TCPCLIENT_INITIALIZE;
|
||||
c_TcpClient_SetOnConnect(&client, OnConnect);
|
||||
c_TcpClient_SetOnData(&client, OnData);
|
||||
c_TcpClient_SetOnDisconnect(&client, OnDisconnect);
|
||||
c_TcpClient_SetOnError(&client, OnError);
|
||||
|
||||
c_err_t err = c_TcpClient_Connect(&client, AF_INET, "127.0.0.1", "1313", 0, NULL);
|
||||
|
||||
c_TcpClientReactor_t* reactor = NULL;
|
||||
c_TcpClientPollReactor_Create(&reactor, NULL);
|
||||
c_TcpClient_SetReactor(&client, reactor);
|
||||
|
||||
while (client.is_linked) {
|
||||
c_TcpClient_PollEvents(&client, 1000, NULL);
|
||||
}
|
||||
|
||||
c_TcpClient_Destroy(&client);
|
||||
c_Socket_Destroy();
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user