Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <WinSock2.h>
- #include <WS2tcpip.h>
- #include <stdio.h>
- using namespace std;
- #pragma comment(lib, "Ws2_32.lib")
- #define PORT_NUMBER 1337
- #define BUFFER_LENGTH 500
- int ShowError();
- void SendMessageToClient(SOCKET soc, char* msg);
- int main()
- {
- WSADATA wsaData;
- int Result;
- Result = WSAStartup(MAKEWORD(2, 2), &wsaData);
- if (Result != 0)
- {
- WSACleanup();
- return ShowError();
- }
- SOCKET ListenSocket = INVALID_SOCKET;
- ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (ListenSocket == INVALID_SOCKET)
- {
- WSACleanup();
- return ShowError();
- }
- SOCKADDR_IN ServerInfo;
- ServerInfo.sin_port = htons(PORT_NUMBER);
- ServerInfo.sin_family = AF_INET;
- ServerInfo.sin_addr.s_addr = ADDR_ANY;
- //bind socket
- Result = bind(ListenSocket, (SOCKADDR*)&ServerInfo, sizeof(ServerInfo));
- if (Result == SOCKET_ERROR)
- {
- WSACleanup();
- return ShowError();
- }
- listen(ListenSocket, 1); //only waiting for 1 client
- SOCKET tempSock = INVALID_SOCKET;
- while (tempSock == INVALID_SOCKET)
- {
- cout << "Waiting for incoming connections..\n";
- tempSock = accept(ListenSocket, 0, 0);
- }
- cout << "\nClient Connected!\n";
- SendMessageToClient(tempSock, "Test message\n");
- Sleep(10);
- SendMessageToClient(tempSock, "Another message!\n");
- shutdown(ListenSocket, SD_SEND);
- closesocket(ListenSocket);
- WSACleanup();
- system("PAUSE > NUL");
- return 0;
- }
- void SendMessageToClient(SOCKET soc, char* msg)
- {
- int bSend = send(soc, msg, (int)strlen(msg), 0);
- printf("\n\nBytes Sent: %d\n\n", bSend);
- }
- int ShowError()
- {
- MessageBox(NULL, "An error occured.", 0, 0);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement