TCP通信流程
Socket函数
TCP通信实现(服务器端)
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() {//1.创建socketint lfd = socket(AF_INET, SOCK_STREAM, 0);if(lfd == -1) {perror("socket");exit(0);}//2.绑定struct sockaddr_in saddr;saddr.sin_family = PF_INET;inet_pton(AF_INET, "192.168.245.129", &saddr.sin_addr.s_addr);saddr.sin_port = htons(9999);int ret = bind(lfd, (struct sockaddr*)&saddr, sizeof(saddr));if(ret == -1) {perror("bind");return 0;}//3.监听ret = listen(lfd, 8);if(ret == -1) {perror("listen");return 0;}//4.接受struct sockaddr_in clientaddr;int len = sizeof(clientaddr);int cfd = accept(lfd, (struct sockaddr*)&clientaddr, &len);if(cfd == -1) {perror("accept");return -1;}//输出客户端的信息char clientIP[16];inet_ntop(AF_INET, &clientaddr.sin_addr.s_addr, clientIP, sizeof(clientIP));unsigned short clientPort = ntohs(clientaddr.sin_port);printf("client ip is %s, client port is %d\n", clientIP, clientPort);//5.获取客户端数据 while(1) {char receiveBuf[1024] = {0};int llen = read(cfd, receiveBuf, sizeof(receiveBuf));if(llen == -1) {perror("read");exit(0);} else if(llen > 0) {printf("receive client data: %s\n", receiveBuf);} else if (llen == 0) {printf("client closed...");break;}//给客户端发送数据char * data = "hello, i`m server";write(cfd, data, strlen(data));}//关闭文件描述符close(cfd);close(lfd);
}
TCP通信实现(客户端)
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() {//创建套接字int lfd = socket(AF_INET, SOCK_STREAM, 0);if(lfd == -1) {perror("socket");exit(-1);}//连接服务器struct sockaddr_in serveraddr;inet_pton(AF_INET, "192.168.245.129", &serveraddr.sin_addr.s_addr);serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(9999);int ret = connect(lfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr));if(ret == -1) {perror("connect");_exit(-1);}//通信while(1) {char * data = "hello, i`m client";write(lfd, data, strlen(data));char receiveBuf[1024] = {0};int len = read(lfd, receiveBuf, sizeof(receiveBuf));if(len == -1) {perror("read");exit(0);} else if(len > 0) {printf("receive server data: %s\n", receiveBuf);} else if (len == 0) {printf("server closed...");}}close(lfd);
}
TCP三次握手
TCP滑动窗口
TCP四次挥手