initial commit

This commit is contained in:
Rokas Puzonas 2024-01-27 12:41:02 +02:00
commit f7f6d57215
5 changed files with 114 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
client
server

6
Makefile Normal file
View File

@ -0,0 +1,6 @@
client: client.c
gcc -o client client.c
server: server.c
gcc -o server server.c

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Mini Chat Server
Tutorial: https://www.youtube.com/watch?v=gGfTjKwLQxY

48
client.c Normal file
View File

@ -0,0 +1,48 @@
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
#include <unistd.h>
#define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0]))
int main() {
int port = 12345;
int stdin_fd = 0;
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd == -1) {
fprintf(stderr, "Failed to open socket\n");
return -1;
}
struct sockaddr_in addr = { AF_INET, htons(port), 0 };
if (connect(client_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
fprintf(stderr, "Failed to connect\n");
return -1;
}
while (true) {
struct pollfd fds[] = {
{ .fd = stdin_fd , POLLIN, 0 },
{ .fd = client_fd, POLLIN, 0 }
};
poll(fds, ARRAY_LEN(fds), -1);
char buffer[256] = { 0 };
if (fds[0].revents & POLLIN) {
int read_bytes = read(stdin_fd, buffer, sizeof(buffer) - 1);
send(client_fd, buffer, read_bytes, 0);
} else if (fds[1].revents & POLLIN) {
if (recv(client_fd, buffer, sizeof(buffer) - 1, 0) == 0) {
return 0;
}
printf("%s\n", buffer);
}
}
return 0;
}

55
server.c Normal file
View File

@ -0,0 +1,55 @@
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
#include <unistd.h>
#define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0]))
int main() {
int port = 12345;
int stdin_fd = 0;
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
fprintf(stderr, "Failed to open socket\n");
return -1;
}
int on = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in addr = { AF_INET, htons(port), 0 };
if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
fprintf(stderr, "Failed to bind\n");
return -1;
}
listen(server_fd, 10);
int client_fd = accept(server_fd, NULL, NULL);
while (true) {
struct pollfd fds[] = {
{ .fd = stdin_fd , POLLIN, 0 },
{ .fd = client_fd, POLLIN, 0 }
};
poll(fds, ARRAY_LEN(fds), -1);
char buffer[256] = { 0 };
if (fds[0].revents & POLLIN) {
int read_bytes = read(stdin_fd, buffer, sizeof(buffer) - 1);
send(client_fd, buffer, read_bytes, 0);
} else if (fds[1].revents & POLLIN) {
if (recv(client_fd, buffer, sizeof(buffer) - 1, 0) == 0) {
return 0;
}
printf("%s\n", buffer);
}
}
return 0;
}