1、windows上加载socket库
链接输入ws2_32.lib
代码code:
#ifdef _WIN32
#include<windows.h>
#else
#include <sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<cstring>
#include<arpa/inet.h>
#include<netinet/in.h>
#define closesocket close
#endif
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<thread>
using namespace std;
class TcpThread
{
public:
void Main()
{
char buf[1024] = { 0 };
for (;;)
{
int recvlen = recv(client, buf, sizeof(buf) - 1, 0);
if (recvlen <= 0)break;
buf[recvlen] = '\0';
if (strstr(buf, "quit") != NULL)
{
char re[] = "quit success\n";
send(client, re, sizeof(re) + 1, 0);
break;
}
int sendlen = send(client, "ok!!\n",sizeof("ok!!\n"), 0);
printf("recv %s\n", buf);
}
closesocket(client);
delete this;
}
int client = 0;
};
int main(int argc, char* argv[])
{
#ifdef _WIN32
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
#endif
//调用句柄
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
{
printf("create socket failed\n");
return -1;
}
unsigned short port = 8181;
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 = htons(0);
if (bind(sock, (sockaddr*)&saddr, sizeof(saddr)) != 0)
{
printf("bind port %d failed\n", port);
return -2;
}
printf("bind port %d success\n", port);
//printf("[%d]", sock);
listen(sock, 10);//第二个参数位套接字请求长度
//端口号和地址
for (;;)
{
sockaddr_in caddr; //返回结构体大小和地址
#ifdef WIN32
int len = sizeof(struct sockaddr);
#else
socklen_t len = sizeof(caddr);
#endif
int client = accept(sock, (sockaddr*)&caddr, &len); //这个sock建立链接
if (client <= 0)break;
printf("Aacept client %d\n", client);
char* ip = inet_ntoa(caddr.sin_addr);
unsigned short cport = ntohs(caddr.sin_port);
printf("client ip is %s,port is %d\n", ip, port);
TcpThread* th = new TcpThread;
th->client = client;
thread sth(&TcpThread::Main, th);//th入口函数
sth.detach(); //线程分离
}
#ifdef _WIN32
closesocket(sock);
#else
close(sock);
#endif
//可以 define close closesocket
getchar();
return 0;
}