mirror of
https://gitlab.fdmci.hva.nl/technische-informatica-sm3/ti-projectten/rooziinuubii79.git
synced 2025-08-03 20:04:58 +00:00
Made cpp into client instead of server
This commit is contained in:
@@ -1,33 +1,54 @@
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <boost/asio.hpp>
|
||||
#include <string>
|
||||
|
||||
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
|
||||
using boost::asio::ip::tcp;
|
||||
|
||||
using namespace std;
|
||||
int main() {
|
||||
try {
|
||||
// Object creation
|
||||
boost::asio::io_context io_context;
|
||||
|
||||
int main()
|
||||
{
|
||||
sockaddr_in serverAddress;
|
||||
serverAddress.sin_family = AF_INET;
|
||||
serverAddress.sin_port = htons(4204);
|
||||
serverAddress.sin_addr.s_addr = INADDR_ANY;
|
||||
// Resolve the server address and port
|
||||
tcp::resolver resolver(io_context);
|
||||
tcp::resolver::results_type endpoints = resolver.resolve("127.0.0.1", "4024");
|
||||
|
||||
bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
|
||||
// Create and connect the socket
|
||||
tcp::socket socket(io_context);
|
||||
boost::asio::connect(socket, endpoints);
|
||||
|
||||
listen(serverSocket, 5);
|
||||
std::cout << "Connected to the server." << std::endl;
|
||||
|
||||
int clientSocket = accept(serverSocket, nullptr, nullptr);
|
||||
// Receive initial message from the server
|
||||
boost::asio::streambuf buffer;
|
||||
boost::asio::read_until(socket, buffer, "\n");
|
||||
std::istream is(&buffer);
|
||||
std::string initial_message;
|
||||
std::getline(is, initial_message);
|
||||
std::cout << "Initial message from server: " << initial_message << std::endl;
|
||||
|
||||
char buffer[1024] = {0};
|
||||
recv(clientSocket, buffer, sizeof(buffer), 0);
|
||||
cout << "Message from client: " << buffer << endl;
|
||||
// Send and receive messages
|
||||
while (true) {
|
||||
// Send a message to the server
|
||||
std::string message;
|
||||
std::cout << "Enter message: ";
|
||||
//read directly from the console and feed with cin to the message variable
|
||||
std::getline(std::cin, message);
|
||||
message += "\n"; // Add newline to mark the end of the message
|
||||
boost::asio::write(socket, boost::asio::buffer(message));
|
||||
|
||||
// Receive a response from the server
|
||||
boost::asio::streambuf response_buffer;
|
||||
boost::asio::read_until(socket, response_buffer, "\n");
|
||||
std::istream response_stream(&response_buffer);
|
||||
std::string reply;
|
||||
std::getline(response_stream, reply);
|
||||
std::cout << "Reply from server: " << reply << std::endl;
|
||||
}
|
||||
|
||||
} catch (std::exception& e) {
|
||||
std::cerr << "Exception: " << e.what() << std::endl;
|
||||
}
|
||||
|
||||
close(serverSocket);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// https://www.geeksforgeeks.org/socket-programming-in-cpp/
|
||||
}
|
Reference in New Issue
Block a user