Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Client.cpp
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <iostream>
- #include <string>
- #pragma comment(lib, "Ws2_32.lib")
- #define SERVER_IP "127.0.0.1"
- #define PORT 8080
- int main() {
- WSADATA wsaData;
- SOCKET clientSocket;
- sockaddr_in serverAddr;
- char buffer[1024];
- std::string name;
- // Initialize WinSock
- if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
- std::cerr << "WSAStartup failed.\n";
- return 1;
- }
- // Create socket
- clientSocket = socket(AF_INET, SOCK_STREAM, 0);
- if (clientSocket == INVALID_SOCKET) {
- std::cerr << "Socket creation failed.\n";
- WSACleanup();
- return 1;
- }
- // Set server address
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_port = htons(PORT);
- if (InetPtonA(AF_INET, SERVER_IP, &serverAddr.sin_addr) <= 0) {
- std::cerr << "Invalid address or address not supported.\n";
- closesocket(clientSocket);
- WSACleanup();
- return 1;
- }
- // Connect to server
- if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
- std::cerr << "Connection failed.\n";
- closesocket(clientSocket);
- WSACleanup();
- return 1;
- }
- // Send name to server
- std::cout << "Enter your name: ";
- std::cin >> name;
- std::string message = "N" + name;
- send(clientSocket, message.c_str(), message.size(), 0);
- // Receive response from server
- int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
- if (bytesReceived > 0) {
- buffer[bytesReceived] = '\0';
- std::cout << "Server: " << buffer << "\n";
- }
- // Wait for "P" message
- bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
- if (bytesReceived > 0) {
- buffer[bytesReceived] = '\0';
- if (std::string(buffer, bytesReceived) == "P") {
- std::cout << "Server sent: P\n";
- // Prompt user to enter "OK"
- std::string userInput;
- std::cout << "Enter 'OK': ";
- std::cin >> userInput;
- // Send "OK" back to server
- if (userInput == "OK") {
- send(clientSocket, userInput.c_str(), userInput.size(), 0);
- }
- else {
- std::cerr << "Invalid input. Closing connection.\n";
- }
- }
- }
- closesocket(clientSocket);
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement