0% found this document useful (0 votes)
12 views2 pages

Message

Uploaded by

madara10932
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Message

Uploaded by

madara10932
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <string>
#include <WS2tcpip.h>
#include <winsock2.h>

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

int main() {
// Initialize Winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);

int wsOk = WSAStartup(ver, &wsData);


if (wsOk != 0) {
std::cerr << "Can't initialize Winsock! Quitting" << std::endl;
return -1;
}

// Create a socket
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Can't create a socket! Quitting" << std::endl;
WSACleanup();
return -1;
}

// Bind the ip address and port to a socket


sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY;

bind(serverSocket, (sockaddr*)&hint, sizeof(hint));

// Tell Winsock the socket is for listening


listen(serverSocket, SOMAXCONN);

// Wait for a connection


sockaddr_in client;
int clientSize = sizeof(client);

SOCKET clientSocket = accept(serverSocket, (sockaddr*)&client, &clientSize);


if (clientSocket == INVALID_SOCKET) {
std::cerr << "Can't accept client connection! Quitting" << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}

// Close server socket (not needed anymore)


closesocket(serverSocket);

// While loop: accept and echo message back to client


char buf[4096];
while (true) {
ZeroMemory(buf, 4096);

// Wait for client to send data


int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR) {
std::cerr << "Error in recv(). Quitting" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}

if (bytesReceived == 0) {
std::cerr << "Client disconnected" << std::endl;
break;
}

// Echo message back to client


send(clientSocket, buf, bytesReceived + 1, 0);
}

// Close the socket


closesocket(clientSocket);

// Cleanup Winsock
WSACleanup();

return 0;
}

You might also like