服务端代码:
#include "SocketAddress.h"
#include "SocketImpl.h"
#include "TcpClient.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
LinWin::CSocketAddress addr(NET_DEFAULT_IP, 6666);
LinWin::CSocketImpl server;
LinWin::CSocketAddress clientAddr;
LinWin::CTcpClient sockClient;
do
{
if (sockClient.Create(true) != 0)
{
cout << "Memory is not enough." << endl;
break;
}
if (server.Create() != 0)
{
cout << "Create socket error." << endl;
break;
}
if (server.Bind(addr) != 0)
{
cout << "Bind address errror." << endl;
break;
}
if (server.Listen(2) != 0)
{
cout << "Listen error." << endl;
break;
}
if (server.Accept(sockClient.Handle(), clientAddr) != 0)
{
cout << "Accept error." << endl;
break;
}
cout << "recevie a connect: " << clientAddr.ToString() << endl;
char buf[1024] = { 0 };
int ret = 0;
if (sockClient.SetRecvTimeOut(30 * 1000) != 0)
cout << "set recv timeout failed." << endl;
LinWin::CSocketImpl* pClient = sockClient.Handle();
while (1)
{
ret = sockClient.Recv(buf, 1023);
if (ret == NET_SOCKET_ERROR)
{
if (pClient->SocketError() == NET_ETIMEDOUT)
cout << "Receive time out." << endl;
break;
}
if (ret == NET_ETIMEDOUT)
cout << "Receive time out." << endl;
buf[ret] = '\0';
if (strcmp("quit", buf) == 0)
{
cout << "Server quit." << endl;
break;
}
if (ret == 0)
{
sockClient.Close();
cout << "Client is already closed." << endl;
break;
}
cout << "recv: " << buf << endl;
}
} while (0);
server.Close();
return 0;
}
客户端代码:
#include "SocketAddress.h"
#include "SocketImpl.h"
#include "TcpClient.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
LinWin::CTcpClient client;
LinWin::CSocketAddress addr("127.0.0.1", 6666);
do
{
if (client.Create() != 0)
{
cout << "create socket error." << endl;
break;
}
if (client.Connect(addr) != 0)
{
cout << "connect error." << endl;
break;
}
string strText;
int ret = 0;
while (1)
{
cout << "Enter a message: ";
getline(cin, strText);
ret = client.Sendn(strText.c_str(), strText.length());
if (ret == NET_SOCKET_ERROR)
break;
if (strcmp(strText.c_str(), "quit") == 0 || strcmp(strText.c_str(), "close") == 0)
break;
cout << "send " << ret << "bytes" << endl;
}
} while (0);
client.Close();
}
在Windows平台上,需要加载套接字库。