Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <netinet/in.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <pthread.h>
- #define BUFF_SIZE (1 << 10)
- static int sockfd;
- void *thRoutineRead(void *arg) {
- char buffer[BUFF_SIZE + 1];
- while (fgets(buffer, BUFF_SIZE, stdin))
- {
- write(sockfd, buffer, strlen(buffer));
- }
- close(sockfd); // se inchide socket-ul
- return NULL;
- }
- void *thRoutineDisplay(void *arg) {
- char buffer[BUFF_SIZE + 1];
- int r;
- while ((r = read(sockfd, buffer, BUFF_SIZE)) > 0)
- {
- buffer[r] = 0;
- printf("Received: %s", buffer);
- }
- return NULL;
- }
- int main(void) {
- struct sockaddr_in server; // structura sockaddr pentru stocarea adresei si portului destinatie la care se va realiza conexiunea
- if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) // crearea socket-ului TCP
- {
- perror("socket");
- exit(1);
- }
- memset(&server, 0, sizeof(server)); // initializarea cu 0 a structurii sockaddr
- server.sin_family = AF_INET; // setarea modului AF_INET obligatoriu pentru aceasta structura
- server.sin_addr.s_addr = inet_addr("127.0.0.1"); // setarea adresei ip la care sa se realizeze conexiunea (in acest caz 127.0.01 - localhost)
- server.sin_port = htons(4556); // setarea portului
- if ((connect(sockfd, (struct sockaddr *)&server, sizeof(server))) < 0) // realizarea conexiunii cu serverul
- {
- perror("connect");
- exit(1);
- }
- printf("Connected\n");
- pthread_t thRead;
- if (pthread_create(&thRead, NULL, thRoutineRead, NULL) != 0) {
- exit(EXIT_FAILURE);
- }
- pthread_t thWrite;
- if (pthread_create(&thWrite, NULL, thRoutineDisplay, NULL) != 0) {
- exit(EXIT_FAILURE);
- }
- pthread_join(thRead, NULL);
- pthread_join(thWrite, NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement