我一直试图通过以下代码弄清楚网络服务器是如何工作的:
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
# if defined(_MSC_VER)
# ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE (1)
# endif
# pragma warning(disable : 4996)
# endif
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
}
while (1)
{
new_socket = accept(s, (struct sockaddr *)&client, &c);
puts("Connection accepted");
//Reply to client
message =
"HTTP/1.1 200 OK\n"
"Content-Type: text/html\n"
"Content-Length: 5\n"
"\n"
"sadasdsa";
send(new_socket, message, strlen(message), 0);
}
getchar();
closesocket(s);
WSACleanup();
return 0;
}
此代码出现的问题是〜每隔一个连接被拒绝并随机工作。
我尝试添加closesocket(new_socket)
和循环结束,但我甚至没有收到localhost:8888
的回复。