WinSock2 实现简单服务器

不管用啥语言写,原理都是差不多的,用Server Socket持续监听某个端口,每次accept到一个请求,就对这个Client Socket的发送的内容进行接收、分析,再发送给客户端一些信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// ConsoleApplication4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#ifndef _MSC_VER
#define _WIN32_WINNT 0x0501
#endif
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <Windows.h>

#ifdef _MSC_VER
#pragma warning(disable: 4996)
#endif

#define BUFSIZE 1024

#pragma comment(lib, "Ws2_32.lib")

typedef struct
{
char* name;
char* value;
} Header;

typedef struct
{
char* protocol;
char* statusCode;
int headersSize;
Header* headers;
char* body;
} HttpResponseMessage;

void send_http_response_message(SOCKET socket, HttpResponseMessage httpResponseMessage);

int main()
{
int result = 0;
WSADATA wsaData;
SOCKET netSocket;

struct addrinfo* resultAddrInfo = NULL;
struct addrinfo hintsAddrInfo;

result = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (result)
{
printf("Error code %d\n", result);
return 0;
}

ZeroMemory(&hintsAddrInfo, sizeof(hintsAddrInfo));
hintsAddrInfo.ai_family = AF_INET;
hintsAddrInfo.ai_socktype = SOCK_STREAM;
hintsAddrInfo.ai_protocol = IPPROTO_TCP;
hintsAddrInfo.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "6680", &hintsAddrInfo, &resultAddrInfo);

netSocket = socket(
resultAddrInfo->ai_family,
resultAddrInfo->ai_socktype,
resultAddrInfo->ai_protocol
);

if (netSocket == INVALID_SOCKET)
{
printf("invalid socket\n");
return 0;
}

result = bind(
netSocket,
resultAddrInfo->ai_addr,
(int)resultAddrInfo->ai_addrlen
);

if (result == SOCKET_ERROR)
{
printf("bind failed\n");
return 0;
}

result = listen(netSocket, SOMAXCONN);

if (result == SOCKET_ERROR)
{
printf("listen failed\n");
return 0;
}

printf("Open http://localhost:6680/\n");

while (1)
{
SOCKET clientSocket = accept(netSocket, NULL, NULL);

if (clientSocket == INVALID_SOCKET) continue;

printf("receive a client\n");

HttpResponseMessage hrm;

hrm.protocol = "HTTP/1.1";
hrm.statusCode = "200 OK";
Header* headers = (Header*)malloc(sizeof(Header) * 1);

if (headers != NULL)
{
headers[0].name = (char*)malloc(sizeof(char) * 20);
if (headers[0].name != NULL)
strcpy(headers[0].name, "Content-Type");

headers[0].value = (char*)malloc(sizeof(char) * 20);
if (headers[0].value != NULL)
strcpy(headers[0].value, "text/html");

}

hrm.headers = headers;
hrm.headersSize = 1;
hrm.body = (char*)malloc(sizeof(char) * 1024);

if (hrm.body != NULL)
strcpy(
hrm.body,
"#<span style=\"color:blue;\">include</span> &lt;stdio.h&gt;<br /><br />"
"<span style=\"color:red;\">int</span> main() {<br />"
"&emsp;<span style=\"color: #ffa500;\">printf</span>(<span style=\"color: green;\">\"Hello World!\"</span>);<br />"
"}"
"<script>alert('Welcome to SIPC115!');</script>"
);

send_http_response_message(clientSocket, hrm);

printf("send message finished\n");
closesocket(clientSocket);
}
}


void send_http_response_message(
const SOCKET socket,
const HttpResponseMessage httpResponseMessage
)
{
char contentLength[33];

send(socket, httpResponseMessage.protocol, strlen(httpResponseMessage.protocol), 0);
send(socket, " ", 1, 0);
send(socket, httpResponseMessage.statusCode, strlen(httpResponseMessage.statusCode), 0);
send(socket, "\n", 1, 0);

send(
socket,
"Content-Length: ",
16,
0
);

itoa(strlen(httpResponseMessage.body), contentLength, 10);

send(
socket,
contentLength,
strlen(contentLength),
0
);

send(
socket,
"\n",
1,
0
);

for (int i = 0; i < httpResponseMessage.headersSize; i++)
{
send(
socket,
httpResponseMessage.headers[i].name,
strlen(httpResponseMessage.headers[i].name),
0
);
send(socket, ": ", 2, 0);
send(
socket,
httpResponseMessage.headers[i].value,
strlen(httpResponseMessage.headers[i].value),
0
);
send(socket, "\n", 1, 0);
}
send(socket, "\n", 1, 0);
send(socket, httpResponseMessage.body, strlen(httpResponseMessage.body), 0);
}

上面没有写接收内容的功能,不过不难,差不多就是下面的样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define BUFSIZE 1024

// ......

char recvBuf[BUFSIZE];
int result = 0;
// ......

while ((result = recv(clientSocket, recvBuf, BUFSIZE, 0)) > 0)
{
content = content.append(recvBuf);
printf("%d, ", result);
if (result < BUFSIZE) break;
}

//......

result表示每次接收到的字节数,接收状态下,result大于0,并小于等于缓冲区大小,即BUFSIZE。

当然,最好不要直接使用std::string的append,可能会出现乱码等情况。

先写这么多。