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
|
#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define _WIN32_WINNIT 0x0500
#include <windows.h>
WSADATA wsa;
SOCKET sock, newsock;
int c;
int clientnum;
struct sockaddr_in server, client;
DWORD WINAPI ProcessClient(LPVOID lpParam) {
SOCKET newSock = (SOCKET)lpParam;
// Send and receive data.
char buf[256];
char newbuf[256];
char cnumchar[5];
strcpy(buf, "Hello Client #: ");
itoa(clientnum, cnumchar, 10);
strcat(buf, cnumchar);
sendto(newSock, buf, sizeof(buf), 0, NULL, NULL);
char sendbuf[256];
strcpy(sendbuf, "a");
while (1)
{
if (recv(newSock, newbuf, sizeof(newbuf), 0) == 0 || recv(newSock, newbuf, sizeof(newbuf), 0) == -1) {
printf("\nClient disconnected");
clientnum--;
}
else if (send(newSock, sendbuf, sizeof(sendbuf), 0) == 0 || send(newSock, sendbuf, sizeof(sendbuf), 0) == -1) {
printf("\nClient Disconnected!");
clientnum--;
}
}
}
int main()
{
printf("Initializing Winsock...\n");
int ret = WSAStartup(MAKEWORD(2, 2), &wsa);
if (ret != 0)
{
printf("Initialization Failed. Error: %d", ret);
return 1;
}
printf("Initialized.\n");
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
printf("Could not create socket! Error: %d\n", WSAGetLastError());
return 1;
}
//textcolor(2);
printf("Socket Created!\n");
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(3939);
//bind
if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed! Error: %d\n", WSAGetLastError());
closesocket(sock);
getch();
return 1;
}
printf("Binded!\n");
// listen
if (listen(sock, 1) == SOCKET_ERROR) {
printf("Listen failed! Error: %d\n", WSAGetLastError());
closesocket(sock);
return 1;
}
printf("Now Listening...\n");
do {
newsock = SOCKET_ERROR;
do {
newsock = accept(sock, NULL, NULL);
} while (newsock == SOCKET_ERROR);
printf("Client Connected!");
DWORD dwThreadId;
CreateThread(NULL, 0, ProcessClient, (LPVOID)newsock, 0, &dwThreadId);
clientnum++;
} while (true);
|