mini-chat-server/client.c
2024-01-27 12:41:02 +02:00

49 lines
1.1 KiB
C

#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;
}