Archived
1
0
Fork 0

Compare commits

..

5 commits

2 changed files with 29 additions and 15 deletions

View file

@ -2,6 +2,7 @@
#include <cstring> #include <cstring>
#include <iostream> #include <iostream>
#include <netinet/in.h> #include <netinet/in.h>
#include <ostream>
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
@ -10,8 +11,12 @@ using std::cout, std::cin, std::endl, std::string;
int main() { int main() {
struct Message { struct Message {
char * content; string content;
string username; string username;
string toString() {
return "User '" + username + "' wrote:\n" + content;
}
}; };
int clientSocket = socket(AF_INET, SOCK_STREAM, 0); int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
@ -21,19 +26,30 @@ int main() {
serverAdress.sin_port = htons(8080); serverAdress.sin_port = htons(8080);
serverAdress.sin_addr.s_addr = inet_addr("127.0.0.50"); serverAdress.sin_addr.s_addr = inet_addr("127.0.0.50");
int connectStatus = connect(clientSocket, (struct sockaddr *)&serverAdress,
sizeof(serverAdress));
if (connectStatus != 0) {
cout << "Failed to connect";
return connectStatus;
} else {
cout << "CONNECTED!" << endl;
}
while (true) { while (true) {
Message message; Message message;
cout << "Type message to server: "; cout << "Type message to server: ";
cin >> message.content; cin >> message.content;
cout << endl;
message.username = "Client 1";
if (strcmp(message.content, "exit") == 0) { if (message.content == "exit") {
cout << "BYE!" << endl;
break; break;
} }
cout << "Sending message to server as user: " << message.username << endl; cout << endl;
send(clientSocket, message.content, strlen(message.content), 0); message.username = "Client 1";
send(clientSocket, message.toString().data(),
strlen(message.toString().data()), 0);
} }
close(clientSocket); close(clientSocket);

View file

@ -1,6 +1,7 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#include <iostream> #include <iostream>
#include <netinet/in.h> #include <netinet/in.h>
#include <ostream>
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
@ -8,12 +9,7 @@ using std::cout, std::endl, std::string;
int main() { int main() {
struct Message { cout << "Initializing server" << endl;
string content;
string username;
};
cout << "Initializing server";
int serverSocket = socket(AF_INET, SOCK_STREAM, 0); int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == -1) { if (serverSocket == -1) {
// TODO error // TODO error
@ -40,9 +36,11 @@ int main() {
// TODO error // TODO error
} }
char buffer[1024] = { 0 }; while (true) {
recv(clientSocket, buffer, sizeof(buffer), 0); char buffer[1024] = {0};
cout << "Message from client " << buffer << endl; recv(clientSocket, buffer, sizeof(buffer), 0);
cout << buffer << endl;
}
close(serverSocket); close(serverSocket);