Created
January 14, 2024 00:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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