Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <winsock2.h>
- #include <iostream>
- #include <sstream>
- #include <string>
- #include <fstream>
- #include <locale>
- #include <vector>
- #include <algorithm>
- #pragma warning(disable: 4996)
- #pragma comment(lib, "Ws2_32.lib")
- using namespace std;
- void insertServerInfo(char* text, size_t bufferSize, const char* serverIP, int serverPort)
- {
- // Create a string stream to manipulate the text
- ostringstream oss;
- // Append the original text to the stream
- oss << text << " Server IP: " << serverIP << ", Port: " << serverPort;
- // Get the resulting string
- std::string result = oss.str();
- // Ensure the result fits into the buffer
- if (result.length() < bufferSize - 1) // Account for null terminator
- {
- // Copy the modified text back to the original buffer
- strncpy_s(text, bufferSize, result.c_str(), _TRUNCATE);
- // Null-terminate the buffer
- text[bufferSize - 1] = '\0';
- }
- else
- {
- cerr << "Modified text exceeds the buffer size. Handle this case accordingly." << endl;
- }
- }
- void handleClient(SOCKET clientSock, const sockaddr_in& sin)
- {
- int retVal;
- do
- {
- char szReq[512];
- retVal = recv(clientSock, szReq, sizeof(szReq) - 1, 0);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to receive data. Error: " << WSAGetLastError() << endl;
- closesocket(clientSock);
- return;
- }
- if (retVal == 0)
- {
- cout << "Client disconnected" << endl;
- closesocket(clientSock);
- return;
- }
- szReq[retVal] = '\0';
- cout << "Data received: " << szReq << endl;
- // Save user input to a text file
- ofstream userInputFile("user_input.txt", ios::app); // Open the file in append mode
- if (userInputFile.is_open())
- {
- userInputFile << szReq << endl;
- userInputFile.close();
- cout << "User input saved to user_input.txt" << endl;
- }
- else
- {
- cerr << "Failed to open user_input.txt for writing." << endl;
- }
- // Insert server info into the user input
- insertServerInfo(szReq, sizeof(szReq), inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
- cout << "Sending response from the server" << endl;
- retVal = send(clientSock, szReq, strlen(szReq), 0);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to send data. Error: " << WSAGetLastError() << endl;
- closesocket(clientSock);
- return;
- }
- ifstream outputFile("output.txt");
- if (outputFile.is_open())
- {
- string line;
- while (getline(outputFile, line))
- {
- cout << line << endl;
- }
- outputFile.close();
- }
- else
- {
- cerr << "Failed to open the file for reading." << endl;
- }
- } while (retVal > 0);
- closesocket(clientSock);
- cout << "Connection closed" << endl;
- }
- int main(void)
- {
- setlocale(LC_ALL, "Russian");
- WORD sockVer;
- WSADATA wsaData;
- int retVal;
- sockVer = MAKEWORD(2, 2);
- WSAStartup(sockVer, &wsaData);
- SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (servSock == INVALID_SOCKET)
- {
- cerr << "Failed to create socket. Error: " << WSAGetLastError() << endl;
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- sockaddr_in sin;
- sin.sin_family = AF_INET;
- // Ввод номера прослушивающего порта с клавиатуры
- cout << "Enter the listening port number: ";
- int port;
- cin >> port;
- sin.sin_port = htons(port);
- // Обработка запросов из любых типов сетей
- sin.sin_addr.s_addr = INADDR_ANY;
- retVal = bind(servSock, reinterpret_cast<LPSOCKADDR>(&sin), sizeof(sin));
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to bind. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- // Output the computer's IP address to the screen
- char hostbuffer[256];
- gethostname(hostbuffer, sizeof(hostbuffer));
- hostent* host_entry;
- host_entry = gethostbyname(hostbuffer);
- char* host_ip = inet_ntoa(*reinterpret_cast<in_addr*>(host_entry->h_addr_list[0]));
- cout << "Computer's IP address: " << host_ip << endl;
- printf("Server is running on %s, port %d\n", host_ip, htons(sin.sin_port));
- while (true)
- {
- retVal = listen(servSock, 10);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to listen to the socket. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- sockaddr_in from;
- int fromlen = sizeof(from);
- SOCKET clientSock = accept(servSock, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
- if (clientSock == INVALID_SOCKET)
- {
- cerr << "Failed to accept the connection. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- cout << "New connection from " << inet_ntoa(from.sin_addr) << ", port " << htons(from.sin_port) << endl;
- handleClient(clientSock, from);
- }
- closesocket(servSock);
- WSACleanup();
- return 0;
- }
- /*void insertServerInfo(char* text, size_t bufferSize, const char* serverIP, int serverPort)
- {
- // Create a string stream to manipulate the text
- std::ostringstream oss;
- // Append the original text to the stream
- oss << text << " Server IP: " << serverIP << ", Port: " << serverPort;
- // Get the resulting string
- std::string result = oss.str();
- // Ensure the result fits into the buffer
- if (result.length() < bufferSize)
- {
- // Copy the modified text back to the original buffer
- strncpy_s(text, bufferSize, result.c_str(), _TRUNCATE);
- }
- else
- {
- cerr << "Modified text exceeds the buffer size. Handle this case accordingly." << endl;
- }
- }
- void handleClient(SOCKET clientSock, const sockaddr_in& sin)
- {
- int retVal;
- do
- {
- char szReq[512];
- retVal = recv(clientSock, szReq, sizeof(szReq) - 1, 0);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to receive data. Error: " << WSAGetLastError() << endl;
- closesocket(clientSock);
- return;
- }
- if (retVal == 0)
- {
- cout << "Client disconnected" << endl;
- closesocket(clientSock);
- return;
- }
- szReq[retVal] = '\0';
- cout << "Data received: " << szReq << endl;
- // Modify the text by inserting server information at the end of each sentence
- insertServerInfo(szReq, sizeof(szReq), inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
- // Tokenize the text into sentences
- std::istringstream iss(szReq);
- std::string sentence;
- // Display and send the modified text back to the client
- while (std::getline(iss, sentence, '.'))
- {
- cout << "Modified text from server: " << sentence << " Server IP: " << inet_ntoa(sin.sin_addr) << ", Port: " << ntohs(sin.sin_port) << "." << endl;
- // Send the modified sentence back to the client
- retVal = send(clientSock, (sentence + " Server IP: " + inet_ntoa(sin.sin_addr) + ", Port: " + std::to_string(ntohs(sin.sin_port)) + ".").c_str(), retVal, 0);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to send data. Error: " << WSAGetLastError() << endl;
- closesocket(clientSock);
- return;
- }
- }
- } while (retVal > 0);
- closesocket(clientSock);
- cout << "Connection closed" << endl;
- }
- int main(void)
- {
- setlocale(LC_ALL, "Russian");
- WORD sockVer;
- WSADATA wsaData;
- int retVal;
- sockVer = MAKEWORD(2, 2);
- WSAStartup(sockVer, &wsaData);
- SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (servSock == INVALID_SOCKET)
- {
- cerr << "Failed to create socket. Error: " << WSAGetLastError() << endl;
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- sockaddr_in sin;
- sin.sin_family = AF_INET;
- // Ввод номера прослушивающего порта с клавиатуры
- cout << "Enter the listening port number: ";
- int port;
- cin >> port;
- sin.sin_port = htons(port);
- // Обработка запросов из любых типов сетей
- sin.sin_addr.s_addr = INADDR_ANY;
- retVal = bind(servSock, reinterpret_cast<LPSOCKADDR>(&sin), sizeof(sin));
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to bind. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- // Output the computer's IP address to the screen
- char hostbuffer[256];
- gethostname(hostbuffer, sizeof(hostbuffer));
- hostent* host_entry;
- host_entry = gethostbyname(hostbuffer);
- char* host_ip = inet_ntoa(*reinterpret_cast<in_addr*>(host_entry->h_addr_list[0]));
- cout << "Computer's IP address: " << host_ip << endl;
- printf("Server is running on %s, port %d\n", host_ip, htons(sin.sin_port));
- while (true)
- {
- retVal = listen(servSock, 10);
- if (retVal == SOCKET_ERROR)
- {
- cerr << "Failed to listen to the socket. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- sockaddr_in from;
- int fromlen = sizeof(from);
- SOCKET clientSock = accept(servSock, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
- if (clientSock == INVALID_SOCKET)
- {
- cerr << "Failed to accept the connection. Error: " << WSAGetLastError() << endl;
- closesocket(servSock);
- WSACleanup();
- system("pause");
- return SOCKET_ERROR;
- }
- cout << "New connection from " << inet_ntoa(from.sin_addr) << ", port " << htons(from.sin_port) << endl;
- handleClient(clientSock, from);
- }
- closesocket(servSock);
- WSACleanup();
- return 0;
- }*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement