TCP通信
- 2. 使用 Socket 進行TCP通信
- 2.1 socket相關函數介紹
- socket()
- bind()
- listen()
- accept()
- connect()
- 2.2 TCP協議 C/S 模型
- 基礎通信代碼
- 最后
2. 使用 Socket 進行TCP通信
Socket通信流程圖如下:
??這里服務器段listen是監聽socket套接字的監聽文件描述符。如果客戶端有連接請求,服務器端會自動和客戶端建立連接,這里的accept函數,只是從已經建立了連接的已連接隊列中取出一個建立的客戶端連接,并返回用于數據傳輸的文件描述符。
2.1 socket相關函數介紹
socket()
//socket函數
#include <sys/types.h>
#include <sys/socket.h>int socket(int domain, int type, int protocol);
返回值:成功返回socket的文件描述符,失敗返回-1,并且通過設置錯誤信息errno
參數:domain:可以選取下面的參數,常用的是AF_INET,AF_INET6,AF_UNIXName Purpose Man pageAF_UNIX, AF_LOCAL Local communication unix(7)AF_INET IPv4 Internet protocols ip(7)AF_INET6 IPv6 Internet protocols ipv6(7)AF_IPX IPX - Novell protocolsAF_NETLINK Kernel user interface device netlink(7)type:可以選取下面的參數,常用的是用于tcp通信的SOCK_STREAM,和udp通信的數據包SOCK_DGRAMSOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.SOCK_DGRAM Supports datagrams (connectionless, unreliable messages of a fixed maximum length).SOCK_SEQPACKET Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each input system call.SOCK_RAW Provides raw network protocol access.SOCK_RDM Provides a reliable datagram layer that does not guarantee ordering.SOCK_PACKET Obsolete and should not be used in new programs; see packet(7).上面的參數還可以或上(|)下面的兩個參數來添加額外屬性:SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the new open file description. Using this flag saves extra calls to fcntl(2) to achieve the same result.SOCK_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful.protocol: 指定這個socket類型使用的協議,如果這個socket類型只有一個協議,那么這個參數設置為0
bind()
#include <sys/types.h>
#include <sys/socket.h>int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
返回值:成功返回0,失敗返回-1,并設置errno值
參數:sockfd: 使用socket函數成功返回的文件描述符addr:socket地址結構體,這里使用sockaddr_in結構體代替,可以接受的客戶端ip和端口struct sockaddr {sa_family_t sa_family;char sa_data[14];}struct sockaddr_in {sa_family_t sin_family; /* address family: AF_INET */in_port_t sin_port; /* port in network byte order */struct in_addr sin_addr; /* internet address */};/* Internet address. */struct in_addr {uint32_t s_addr; /* address in network byte order */};addrlen:sockaddr_in結構體大小,sizeof(addr)
listen()
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>int listen(int sockfd, int backlog);
返回值:成功返回0,失敗返回-1,并設置errno
參數:sockfd:socket文件描述符,同上backlog:排隊建立3次握手隊列和剛剛建立3次握手隊列的鏈接數和,例如可以設置為1024
accept()
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
返回值:成功,系統掉用會返回一個非負的整數,這個整數就是已經連接的socket文件描述符,失敗返回-1,并設置errno值。
參數:sockfd:同上addr:傳出參數,取出的這個連接的socket文件描述符的客戶端地址參數,設置為NULL表示不需要傳出addrlen:傳出地址結構體的大小, sizeof(addr),前面為NULL,則它設為NULL
connect()
#include <sys/types.h>
#include <sys/socket.h>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
返回值:成功返回0,失敗返回-1,并設置errno
參數:sockfd: 客戶端socket文件描述符addr: 傳入參數,指定服務器的地址和端口addrlen: 上面結構體的大小 sizeof(addr)
2.2 TCP協議 C/S 模型
為了方便錯誤處理,可以對上面函數進行封裝后使用
//wrap.h
#ifndef __WRAP_H_
#define __WRAP_H_
void perr_exit(const char *s);
int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr);
int Bind(int fd, const struct sockaddr *sa, socklen_t salen);
int Connect(int fd, const struct sockaddr *sa, socklen_t salen);
int Listen(int fd, int backlog);
int Socket(int family, int type, int protocol);
ssize_t Read(int fd, void *ptr, size_t nbytes);
ssize_t Write(int fd, const void *ptr, size_t nbytes);
int Close(int fd);
#endif//wrap.c
#include <wrap.h>void perr_exit(const char *s)
{perror(s);exit(1);
}
// 確定這是一個什么類型的socket,可以接收哪種協議
int Socket(int family, int type, int protocol)
{int sfd;if ((sfd = socket(family, type, protocol)) < 0)perr_exit("socket error");return sfd;
}// 綁定sfd的ip和端口,成功返回0,失敗返回-1
int Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{int n;// 成功返回0if ((n = bind(fd, sa, salen)) < 0)perr_exit("bind error");return n;
}// 監聽sfd并自動與連接請求建立連接,監聽成功返回0,失敗返回-1
int Listen(int fd, int backlog)
{int n;if ((n = listen(fd, backlog)) < 0)perr_exit("listen error");return n;
}/* 取出一個已經和服務器sfd的socket建立連接的連接隊列中取出一個客戶端sfd,
后兩個都是傳出參數,是客戶端socket的信息
返回客戶端文件描述符*/
int Accept(int sfd, struct sockaddr *sa, socklen_t *clientsocketlenptr)
{int n;
reaccept:if ((n = accept(sfd, sa, clientsocketlenptr)) < 0){// 防止該阻塞函數被無關的信號打斷if ((errno == ECONNABORTED) || (errno == EINTR))goto reaccept;elseperr_exit("accept error");}return n;
}/*客戶端發起連接,sfd為客戶端socket文件描述符,
后兩個參數是服務器端的ip和端口
連接成功返回0,失敗返回-1*/
int Connect(int sfd, const struct sockaddr *sa, socklen_t salen)
{int n;if ((n = connect(sfd, sa, salen)) < 0)perr_exit("connect error");return n;
}/*從cfd文件描述符中讀取數據到 buf 中
成功,返回讀取到的字符串長度,如果返回0表示讀到末尾,失敗返回-1
*/
ssize_t Read(int cfd, void *buf, size_t buflen)
{ssize_t n;
readagain:if ((n = read(cfd, buf, buflen)) == -1){if (errno == EINTR)goto readagain;elsereturn -1;}else if (n == 0){printf("read end of file\n");}return n;
}ssize_t Write(int cfd, const void *buf, size_t buflen)
{ssize_t n;
writeagain:if ((n = write(cfd, buf, buflen)) == -1){if (errno == EINTR)goto writeagain;elsereturn -1;}else if (n == 0){printf("write end of file\n");}return n;
}int Close(int fd)
{int n;if ((n = close(fd)) == -1)perr_exit("close error");return n;
}
基礎通信代碼
服務器單進程處理客戶端連接和數據通信,主要通過while循環來實現。
//server.c
#include <wrap.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <ctype.h>void showClient(const struct sockaddr_in *clientaddr)
{char buf[16];memset(buf, 0x00, sizeof(buf));inet_ntop(AF_INET, &clientaddr->sin_addr.s_addr, buf, sizeof(buf));printf("client family is[%d], ip is[%s] ,port is [%d]----connected\n", clientaddr->sin_family, buf, ntohs(clientaddr->sin_port));
}int main()
{int sfd = Socket(AF_INET, SOCK_STREAM, 0);struct sockaddr_in addr;bzero(&addr, 0x00);addr.sin_family = AF_INET;addr.sin_port = htons(8888);addr.sin_addr.s_addr = htonl(INADDR_ANY);Bind(sfd, (struct sockaddr *)&addr, sizeof(addr));Listen(sfd, 1024);struct sockaddr_in clientaddr;bzero(&clientaddr, 0x00);int cfd;char buf[64];int n;socklen_t len;while (1){n = 0;len = sizeof(clientaddr);cfd = Accept(sfd, (struct sockaddr *)&clientaddr, &len);showClient(&clientaddr);while (1){memset(buf,0x00,sizeof(buf));n = Read(cfd, buf, sizeof(buf));if (n==0){break;}printf("[%d] byte word,client send say:[%s]\n", n, buf);int i = 0;for (i = 0; i < n; i++){buf[i] = toupper(buf[i]);}Write(cfd, buf, n);}}close(cfd);close(sfd);return 0;
}
//client.c
#include <wrap.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <ctype.h>void showClient(const struct sockaddr_in *clientaddr)
{char buf[16];memset(buf, 0x00, sizeof(buf));inet_ntop(AF_INET, &clientaddr->sin_addr.s_addr, buf, sizeof(buf));printf("client family is[%d], ip is[%s] ,port is [%d]----connected\n", clientaddr->sin_family, buf, clientaddr->sin_port);
}int main()
{int cfd = Socket(AF_INET, SOCK_STREAM, 0);struct sockaddr_in addr;bzero(&addr, 0x00);addr.sin_family = AF_INET;addr.sin_port = htons(8888);inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);Connect(cfd, (struct sockaddr *)&addr, sizeof(addr));char words[64];int n;while (1){memset(words, 0x00, sizeof(words));// scanf("%s", words);//讀標準輸入數據n = read(STDIN_FILENO, words, sizeof(words));Write(cfd, words, strlen(words));n = Read(cfd, words, sizeof(words));printf("server reply [%s],byte is [%d]\n", words, n);}return 0;
}
最后
推薦一個零聲教育學習教程,個人覺得老師講得不錯,分享給大家:[Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,
TCP/IP,協程,DPDK等技術內容,點擊立即學習:鏈接