-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
96 lines (77 loc) · 2.65 KB
/
client.cpp
File metadata and controls
96 lines (77 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <unistd.h>
#include <iomanip>
#include <bits/stdc++.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define BUFLEN 2048
#define SERVER_IP_ADDRESS "127.0.0.1"
#define PORT 5300
void *readMessagesFromServer(void *sock_fd_arg){
int *sock_fd = (int *)sock_fd_arg;
char r_buff[BUFLEN];
while(1){
sleep(2);
// Read messages from server and display
bzero(r_buff, sizeof(r_buff));
read(*sock_fd, r_buff, sizeof(r_buff));
std::cout << "\n----------------------------------------" << std::endl;
std::cout << "\n\nServer messages: \n\n" << std::endl;
std::cout << r_buff << std::endl;
std::cout << "----------------------------------------" << std::endl;
}
}
void chat(int sock_fd){
char s_buff[BUFLEN];
while(1){
// Send data to server
bzero(s_buff, sizeof(s_buff));
std::cout << "Enter a message or command to send: ";
std::cout << "\n*****\n";
std::cout << "Available commands: \n" << std::endl;
std::cout << "/whisper - " << "Send data to a particular client based on their ID - [Example usage: /whisper 29 Hello James]" << std::setw(10) << std::endl;
std::cout << "/view - " << "View all connected clients - [Usage: /view]" << std::setw(10);
std::cout << "\n*****\n";
fgets(s_buff, sizeof(s_buff), stdin);
write(sock_fd, s_buff, strlen(s_buff));
}
}
int main(int agrc, char **argv){
int sock_fd;
struct sockaddr_in server;
pthread_t tid;
// Get username
char username[20];
std::cout << "Enter your name: ";
fgets(username, sizeof(username), stdin);
// Create a socket
if((sock_fd = socket(AF_INET, SOCK_STREAM, 0))==-1){
std::cout << "Failed to create a socket!" << std::endl;
exit(1);
}
// Server details
server.sin_addr.s_addr = inet_addr(SERVER_IP_ADDRESS); // server IP address
server.sin_family = AF_INET;
server.sin_port = PORT;
// Connect to server
if(connect(sock_fd, (struct sockaddr*)&server, sizeof(server))==-1){
std::cout << "Failed to connet to server!" << std::endl;
exit(1);
}
// Send user details to sever
if(write(sock_fd, username, strlen(username))==-1){
std::cout << "Failed to register!" << std::endl;
exit(1);
}
// Thread to read messages from server
pthread_create(&tid, NULL, readMessagesFromServer, &sock_fd);
// Interact with other connected clients
chat(sock_fd);
// Close fd on disconnecting
close(sock_fd);
return 0;
}