Skip to content

Instantly share code, notes, and snippets.

@nir9
Created January 14, 2024 00:17
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nir9/f5a7307a47698303653b776a93585a00 to your computer and use it in GitHub Desktop.
Save nir9/f5a7307a47698303653b776a93585a00 to your computer and use it in GitHub Desktop.
Minimalist Chat Server and Client in C - just for fun, not suitable for production
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <poll.h>
#include <unistd.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {
AF_INET,
htons(9999),
0
};
connect(sockfd, &address, sizeof(address));
// stdin - 0
struct pollfd fds[2] = {
{
0,
POLLIN,
0
},
{
sockfd,
POLLIN,
0
}
};
for (;;) {
char buffer[256] = { 0 };
poll(fds, 2, 50000);
if (fds[0].revents & POLLIN) {
read(0, buffer, 255);
send(sockfd, buffer, 255, 0);
} else if (fds[1].revents & POLLIN) {
if (recv(sockfd, buffer, 255, 0) == 0) {
return 0;
}
printf("%s\n", buffer);
}
}
return 0;
}
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <poll.h>
#include <unistd.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {
AF_INET,
htons(9999),
0
};
bind(sockfd, &address, sizeof(address));
listen(sockfd, 10);
int clientfd = accept(sockfd, 0, 0);
// stdin - 0
struct pollfd fds[2] = {
{
0,
POLLIN,
0
},
{
clientfd,
POLLIN,
0
}
};
for (;;) {
char buffer[256] = { 0 };
poll(fds, 2, 50000);
if (fds[0].revents & POLLIN) {
read(0, buffer, 255);
send(clientfd, buffer, 255, 0);
} else if (fds[1].revents & POLLIN) {
if (recv(clientfd, buffer, 255, 0) == 0) {
return 0;
}
printf("%s\n", buffer);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment