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
|
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#define BUFFER_SIZE 1024
#pragma comment(lib, "ws2_32.lib")
void with_error(char *s, int *errCode = NULL)
{
int err = (errCode) ? *errCode : WSAGetLastError();
fprintf(stderr, "%s: %d\n", s, err);
fflush(stderr);
exit(1);
}
int main(int argc, char *argv[])
{
WSADATA wsadata;
SOCKET server_fd, client_fd;
struct sockaddr_in server, client;
int port = 5555, err;
char buf[BUFFER_SIZE];
err = WSAStartup(MAKEWORD(2,2), &wsadata);
if (err != 0)
with_error("Error in WSAStartup", &err);
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == INVALID_SOCKET)
with_error("Error creating socket");
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
/** bind & listen **/
const BOOL optval = TRUE;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval));
err = bind(server_fd, (struct sockaddr *) &server, sizeof(server));
if (err == SOCKET_ERROR)
with_error("Not able to bind the socket");
err = listen(server_fd, 1);
if (err == SOCKET_ERROR)
with_error("Not able to listen on the socket");
printf("SERVER LISTENING ON PORT %d\n", port);
while (1)
{
int clientlen = sizeof(client);
client_fd = accept(server_fd, (struct sockaddr *) &client, &clientlen);
if (client_fd == INVALID_SOCKET)
with_error("Not able to setup a new connection");
bool keepLoop= true;
do
{
int read = recv(client_fd, buf, BUFFER_SIZE, 0);
if (read == 0)
break;
if (read == SOCKET_ERROR)
{
err = WSAGetLastError();
if ((err != WSAENOTCONN) && (err != WSAECONNABORTED) && (err == WSAECONNRESET))
with_error("Error reading from client", &err);
break;
}
char *pbuf = buf;
do
{
int sent = send(client_fd, pbuf, read, 0);
if (sent == SOCKET_ERROR)
{
err = WSAGetLastError();
if ((err != WSAENOTCONN) && (err != WSAECONNABORTED) && (err == WSAECONNRESET))
with_error("Error writing to client", &err);
keepLoop = false;
break;
}
pbuf += sent;
read -= sent;
}
while (read > 0);
}
while (keepLoop);
closesocket(client_fd);
}
WSACleanup();
return 0;
}
| |