-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket_server.c
109 lines (91 loc) · 2.59 KB
/
socket_server.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#define BUFFER_SIZE 1024
DWORD WINAPI receiveMessages(LPVOID lpParam)
{
SOCKET clientSocket = (SOCKET)lpParam;
int bytesReceived;
char buffer[BUFFER_SIZE];
while (1)
{
bytesReceived = recv(clientSocket, buffer, BUFFER_SIZE, 0);
if (bytesReceived > 0)
{
buffer[bytesReceived] = '\0';
printf(buffer);
}
else if (bytesReceived == 0)
{
printf("Client disconnected\n");
break;
}
else
{
fprintf(stderr, "Error receiving data\n");
break;
}
}
closesocket(clientSocket);
return 0;
}
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
{
fprintf(stderr, "Error creating socket\n");
WSACleanup();
return 1;
}
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(8888);
bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
listen(serverSocket, 5);
printf("Server listening on port 8888\n");
while (1)
{
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET)
{
fprintf(stderr, "Error accepting client connection\n");
closesocket(serverSocket);
WSACleanup();
return 1;
}
HANDLE hThread = CreateThread(NULL, 0, receiveMessages, (LPVOID)clientSocket, 0, NULL);
if (hThread == NULL)
{
fprintf(stderr, "Error creating thread\n");
closesocket(clientSocket);
}
else
{
CloseHandle(hThread);
}
char message[BUFFER_SIZE];
int bytesSent;
while (1)
{
fgets(message, sizeof(message), stdin);
message[strcspn(message, "\n")] = '\0';
bytesSent = send(clientSocket, message, strlen(message), 0);
if (bytesSent == SOCKET_ERROR)
{
fprintf(stderr, "Error sending data\n");
break;
}
if (strcmp(message, "exit_server") == 0)
break;
}
}
closesocket(serverSocket);
WSACleanup();
return 0;
}