脱离笔记完成TCP服务器客户端搭建。
//server
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>#define ERR_MSG(msg) do{\fprintf(stderr, "line:%d\n", __LINE__);\perror(msg);\
}while(0)#define IP "192.168.31.69"
#define PORT 8888int main(int argc, const char *argv[])
{int sfd = socket(AF_INET, SOCK_STREAM, 0);if(sfd < 0){ERR_MSG("socket");return -1;}struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(PORT);sin.sin_addr.s_addr = inet_addr(IP);if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0){ERR_MSG("bind");return -1;}printf("bind success\n");if(listen(sfd, 128) < 0){ERR_MSG("listen");return -1;}printf("listen success\n");struct sockaddr_in cin;socklen_t addrlen = sizeof(cin);int newfd = accept(sfd, (struct sockaddr *)&cin, &addrlen);if(newfd < 0){ERR_MSG("accept");return -1;}printf("连接成功\n");char buf[128] = "";ssize_t res = 0;while(1){bzero(buf, sizeof(buf));res = recv(newfd, buf, sizeof(buf), 0);if(res < 0){ERR_MSG("recv");return -1;}else if(0 == res){printf("客户端下线\n");break;}//发送if(send(newfd, buf, sizeof(buf), 0), 0){ERR_MSG("send");return -1;}printf("发送成功\n");}close(sfd); close(newfd);return 0;
}
//client#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>#define ERR_MSG(msg) do{ \fprintf(stderr, "line:%d\n", __LINE__); \perror(msg); \
}while(0)#define IP "192.168.31.69"
#define PORT 8888int main(int argc, const char *argv[])
{int cfd = socket(AF_INET, SOCK_STREAM, 0);if(cfd < 0){ERR_MSG("socket");return -1;}struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(PORT);sin.sin_addr.s_addr = inet_addr(IP);if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0){ERR_MSG("connect");return -1;}printf("connect success\n");char buf[128] = "";ssize_t res = 0;while(1){bzero(buf, sizeof(buf));printf("请输入:");fgets(buf, sizeof(buf), stdin);buf[strlen(buf)-1] = '\0';if(send(cfd, buf, sizeof(buf), 0) < 0){ERR_MSG("send");return -1;}printf("send success\n");bzero(buf, sizeof(buf));res = recv(cfd, buf, sizeof(buf), 0);if(res < 0){ERR_MSG("recv");return -1;}else if(0 == res){printf("server is down\n");break;}printf(" : %s__%d__\n", buf, __LINE__);}close(cfd);return 0;
}