#include <stdio.h>
#ifdef WIN32
#include <WinSock2.h>
#include <Windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#endif
#include <thread>
#ifdef WIN32
#pragma comment(lib, "ws2_32.lib")
#endif
class TcpThread
{
public:
void Main()
{
char buf[1024] = { 0 };
while (1)
{
memset(buf, 0, 1024);
int len1 = recv(client, buf, 1023, 0);
printf("recv: %s\n", buf);
if (len1 <= 0)
break;
if (strstr(buf, "quit") != NULL)
break;
int sendlen = send(client, "ok", 3, 0);
}
#ifdef WIN32
closesocket(client);
#else
close(client);
#endif
delete this;
}
public:
int client = 0;
};
int main(int argc, char* argv[])
{
#ifdef WIN32
WSADATA wsadata = { 0 };
WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif
int s = socket(AF_INET, SOCK_STREAM, 0);
printf("%d ", s);
if (s == -1)
{
printf("Create socket failed.\n");
return -1;
}
unsigned short port = 8080;
if (argc > 1)
{
port = atoi(argv[1]);
}
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = htonl(0);
if (bind(s, (sockaddr*)&saddr, sizeof(saddr)) != 0)
{
printf("bind port %d failed\n", port);
return -2;
}
printf("bind port %d success!\n", port);
listen(s, 10);
while (1)
{
sockaddr_in caddr = { 0 };
#ifdef WIN32
int len = sizeof(sockaddr_in);
#else
socklen_t len = sizeof(sockaddr_in);
#endif
int client = accept(s, (sockaddr*)&caddr, &len);
if (client == -1)
{
printf("accpet failed.\n");
return -3;
}
printf("accept socket:%d\n", client);
char *ip = inet_ntoa(caddr.sin_addr);
printf("ip:%s\n", ip);
unsigned short cport = ntohs(caddr.sin_port);
printf("port:%d\n", cport);
TcpThread *th = new TcpThread();
th->client = client;
std::thread sth(&TcpThread::Main, th);
sth.detach();
}
#ifdef WIN32
closesocket(s);
#else
close(s);
#endif
#ifdef WIN32
WSACleanup();
#endif
getchar();
return 0;
}
|