Compare commits
5 commits
3b782e664a
...
cfb7478ab9
Author | SHA1 | Date | |
---|---|---|---|
cfb7478ab9 | |||
45e779c56f | |||
2a5a735fde | |||
9b2706ed81 | |||
63bd78aeb0 |
2 changed files with 29 additions and 15 deletions
|
@ -2,6 +2,7 @@
|
|||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <netinet/in.h>
|
||||
#include <ostream>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
@ -10,8 +11,12 @@ using std::cout, std::cin, std::endl, std::string;
|
|||
int main() {
|
||||
|
||||
struct Message {
|
||||
char * content;
|
||||
string content;
|
||||
string username;
|
||||
|
||||
string toString() {
|
||||
return "User '" + username + "' wrote:\n" + content;
|
||||
}
|
||||
};
|
||||
|
||||
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
|
||||
|
@ -21,19 +26,30 @@ int main() {
|
|||
serverAdress.sin_port = htons(8080);
|
||||
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) {
|
||||
Message message;
|
||||
cout << "Type message to server: ";
|
||||
cin >> message.content;
|
||||
cout << endl;
|
||||
message.username = "Client 1";
|
||||
|
||||
if (strcmp(message.content, "exit") == 0) {
|
||||
if (message.content == "exit") {
|
||||
cout << "BYE!" << endl;
|
||||
break;
|
||||
}
|
||||
|
||||
cout << "Sending message to server as user: " << message.username << endl;
|
||||
send(clientSocket, message.content, strlen(message.content), 0);
|
||||
cout << endl;
|
||||
message.username = "Client 1";
|
||||
|
||||
send(clientSocket, message.toString().data(),
|
||||
strlen(message.toString().data()), 0);
|
||||
}
|
||||
|
||||
close(clientSocket);
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
#include <arpa/inet.h>
|
||||
#include <iostream>
|
||||
#include <netinet/in.h>
|
||||
#include <ostream>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
@ -8,12 +9,7 @@ using std::cout, std::endl, std::string;
|
|||
|
||||
int main() {
|
||||
|
||||
struct Message {
|
||||
string content;
|
||||
string username;
|
||||
};
|
||||
|
||||
cout << "Initializing server";
|
||||
cout << "Initializing server" << endl;
|
||||
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (serverSocket == -1) {
|
||||
// TODO error
|
||||
|
@ -40,9 +36,11 @@ int main() {
|
|||
// TODO error
|
||||
}
|
||||
|
||||
char buffer[1024] = { 0 };
|
||||
recv(clientSocket, buffer, sizeof(buffer), 0);
|
||||
cout << "Message from client " << buffer << endl;
|
||||
while (true) {
|
||||
char buffer[1024] = {0};
|
||||
recv(clientSocket, buffer, sizeof(buffer), 0);
|
||||
cout << buffer << endl;
|
||||
}
|
||||
|
||||
close(serverSocket);
|
||||
|
||||
|
|
Reference in a new issue