Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <winsock2.h>
- #include <ws2tcpip.h> // Для использования inet_pton
- #include <string>
- #include <iostream>
- #pragma comment(lib, "Ws2_32.lib")
- constexpr const int DEFAULT_BUF_SIZE = 512;
- constexpr const int DEFAULT_PORT = 2003;
- int main(void)
- {
- WSADATA wsaData;
- std::string ip;
- int iResult;
- setlocale(LC_ALL, "RU");
- SOCKET ConnectSocket = INVALID_SOCKET;
- struct sockaddr_in clientService;
- std::string sendbuf;
- char recvbuf[DEFAULT_BUF_SIZE];
- // Init winSock
- iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
- if (iResult != NO_ERROR)
- {
- std::cout << "WSAStartup failed: " << iResult << std::endl;
- return 1;
- }
- // Create Socket
- ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (ConnectSocket == SOCKET_ERROR)
- {
- std::cout << "socket error: " << WSAGetLastError() << std::endl;
- WSACleanup();
- return 1;
- }
- // The sockaddr_in structure specifies the address family,
- // IP address, and port of the server to be connected to.
- std::cout << "Enter server IP: ";
- std::cin >> ip;
- std::cin.get();
- // Use inet_pton to convert IP address from string to binary
- if (inet_pton(AF_INET, ip.c_str(), &(clientService.sin_addr)) <= 0)
- {
- std::cout << "Invalid IP address: " << ip << std::endl;
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- clientService.sin_family = AF_INET;
- clientService.sin_port = htons(DEFAULT_PORT);
- // Connect to server.
- iResult = connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
- if (iResult == SOCKET_ERROR)
- {
- closesocket(ConnectSocket);
- std::cout << "Unable to connect to server: " << WSAGetLastError() << std::endl;
- WSACleanup();
- return 1;
- }
- // Send text strings to the server
- std::cout << "Enter text lines to send to the server. Enter an empty line to finish:\n";
- do
- {
- std::getline(std::cin, sendbuf);
- if (!sendbuf.empty())
- {
- sendbuf += '\n'; // Add newline character as a delimiter
- iResult = send(ConnectSocket, sendbuf.data(), static_cast<int>(sendbuf.length()), 0);
- if (iResult == SOCKET_ERROR)
- {
- std::cout << "send failed: " << WSAGetLastError() << std::endl;
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- // Receive the modified text from the server
- iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUF_SIZE, 0);
- if (iResult > 0)
- {
- recvbuf[iResult] = '\0';
- std::cout << "Modified text from server: " << recvbuf;
- }
- else if (iResult == 0)
- {
- std::cout << "\nConnection closed by server\n";
- break;
- }
- else
- {
- perror("recv");
- break;
- }
- }
- } while (!sendbuf.empty());
- // Cleanup
- closesocket(ConnectSocket);
- WSACleanup();
- return 0;
- }
Add Comment
Please, Sign In to add comment