WinSock 开启 TCP 服务器例子
这个也是在 CSDN 上的不知道几手的代码,原帖还有个客户端的, 我用不着就懒得发了
编译命令
gcc winsock.c -o w.exe -lwsock32 -lWs2_32
// Server
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <IPHlpApi.h>
#include <stdio.h>
#pragma comment(lib, "WS2_32.lib")
int main(int argc, char ** argv)
{
// 初始化 Winsock
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
if(iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
else
{
printf("WSAStartup success: %d\n", iResult);
}
// 获取连接属性
struct addrinfo * result = NULL, * ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
else
{
printf("getaddrinfo success: %d\n", iResult);
}
// 创建 Listen Socket 对象
SOCKET ListenSocket = INVALID_SOCKET;
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// 绑定连接端口
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else
{
printf("bind success %s\n",result->ai_addr);
}
// 开始监听
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
printf("Error at bind(): %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else
{
printf("Listening %s\n",DEFAULT_PORT);
}
// Accept 一个链接(阻塞)
SOCKET ClientSocket = INVALID_SOCKET;
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else
{
puts("A client has connected");
}
// 接受一些数据
char recvbuf[DEFAULT_BUFLEN+1];
do {
memset(recvbuf,0,sizeof(recvbuf));
iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFLEN, 0);
if (iResult > 0) {
// Echo the buffer to the console
recvbuf[DEFAULT_BUFLEN] = 0;
printf("Bytes received: %d, %s\n", iResult, recvbuf);
}
else if (iResult == 0) {
printf("Connection closing ...\n");
}
else {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
} while (iResult > 0);
// shutdown the send half of the connection since no more data will be sent
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// 清理
closesocket(ListenSocket);
WSACleanup();
return 0;
}