服务端代码如下:
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char* argv[])
{
//初始化WSA
WORD sockVersion = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(sockVersion, &wsaData)!=0)
{
return 0;
}
//创建套接字
SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(slisten == INVALID_SOCKET)
{
printf("socket error !");
return 0;
}
//绑定IP和端口
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error !");
}
//开始监听
if(listen(slisten, 5) == SOCKET_ERROR)
{
printf("listen error !");
return 0;
}
//循环接收数据
SOCKET sClient;
sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);
char revData[255];
while (true)
{
printf("等待连接...\n");
sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
if(sClient == INVALID_SOCKET)
{
printf("accept error !");
continue;
}
printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
//接收数据
int ret = recv(sClient, revData, 255, 0);
if(ret > 0)
{
revData[ret] = 0x00;
printf(revData);
}
//发送数据
const char * sendData = "你好,TCP客户端!\n";
send(sClient, sendData, strlen(sendData), 0);
closesocket(sClient);
}
closesocket(slisten);
WSACleanup();
return 0;
}
出现的错误如下:
PS X:\data-struct\data-structure> cd "x:\data-struct\data-structure\" ; if ($?) { g++ server.cpp -o server } ; if ($?) { .\C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x3e): undefined reference to `__imp_WSAStartup'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x6a): undefined reference to `__imp_socket'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0xa8): undefined reference to `__imp_htons'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0xd9): undefined reference to `__imp_bind'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x107): undefined reference to `__imp_listen'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x161): undefined reference to `__imp_accept'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x194): undefined reference to `__imp_inet_ntoa'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x1c6): undefined reference to `__imp_recv'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x230): undefined reference to `__imp_send'
C:\Users\fligh\AppData\Local\Temp\ccJc48Xw.o:server.cpp:(.text+0x243): undefined reference to `__imp_closesocket'
collect2.exe: error: ld returned 1 exit status