restructure and add server/client example
This commit is contained in:
40
server/src/client.cpp
Normal file
40
server/src/client.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
#include "TcpSocket.hpp"
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
char mes[] = "Hello Server!";
|
||||
|
||||
int main()
|
||||
{
|
||||
int sock = TcpSocket::connectt("localhost", 8888);
|
||||
|
||||
if (sock < 0)
|
||||
{
|
||||
printf("Error %d", sock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
char tempBuffer[AS_DEFAULT_BUFFER_SIZE + 1];
|
||||
ssize_t messageLength;
|
||||
|
||||
// You should do an input loop, so the program won't terminate immediately
|
||||
string input;
|
||||
getline(cin, input);
|
||||
while (input != "exit")
|
||||
{
|
||||
TcpSocket::sendt(sock, input.data(), input.size());
|
||||
messageLength = TcpSocket::recvt(sock, tempBuffer, AS_DEFAULT_BUFFER_SIZE);
|
||||
if (messageLength <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
tempBuffer[messageLength] = 0;
|
||||
printf("%s\n", tempBuffer);
|
||||
getline(cin, input);
|
||||
}
|
||||
|
||||
TcpSocket::closet(sock);
|
||||
|
||||
return 0;
|
||||
}
|
34
server/src/server.cpp
Normal file
34
server/src/server.cpp
Normal file
@@ -0,0 +1,34 @@
|
||||
#include "TcpSocket.hpp"
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
// use pthread rw_lock to lock db so you can safy clone .db file
|
||||
|
||||
int main()
|
||||
{
|
||||
// When a new client connected:
|
||||
TcpSocket::OnNewConnectionCallBack onNewConnection = [](int sock, sockaddr_in newSocketInfo)
|
||||
{
|
||||
std::cout << "new User" << std::endl;
|
||||
char tempBuffer[AS_DEFAULT_BUFFER_SIZE + 1];
|
||||
ssize_t messageLength;
|
||||
while ((messageLength = TcpSocket::recvt(sock, tempBuffer, AS_DEFAULT_BUFFER_SIZE)) > 0)
|
||||
{
|
||||
tempBuffer[messageLength] = '\0';
|
||||
TcpSocket::sendt(sock, tempBuffer, messageLength);
|
||||
}
|
||||
std::cout << "del USER" << std::endl;
|
||||
TcpSocket::closet(sock);
|
||||
};
|
||||
|
||||
// Bind the server to a port.
|
||||
int err = TcpSocket::listent("0.0.0.0", 8888, onNewConnection);
|
||||
if (err < 0)
|
||||
{
|
||||
printf("ERROR %d", err);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user