TCP通信的过程为:
一. 服务器端:
1.socket(int domain,int type,int protocol):建立套接字;
2 .bind(int sockid,struct sockaddr *addrp,socklen_t addrlen):绑定端口和地址信息;
3.listen(int sockid,int qsize):监听套接字;
4.fd=accept(int sockid,struct sockaddr *callerid,socklen_t *addrlenp):等待套接字;
5.recv(int fd,void *buf,size_t nbytes,int flags):从套接字接收数据;
6.close(fd) 和close(sockid) 关闭套接字
二.客户端:
1. socket():建立套接字;
2.connect(int sockid,struct sockaddr *serv_addrp,socklen_t addrlen):连接到服务器;
3. send(int sockfd,const void *buf,size_t nbytes,int flags):发送数据到服务器.
4. close(sockid);关闭套接字
TCP通信服务器端程序:
# include <stdio.h> # include <sys/socket.h> # include <arpa/inet.h> # include <string.h> # define MAX_SIZE 256 int main() { int err; int listenfd,connfd; struct sockaddr_in servaddr,clientaddr; int n,addrlen=sizeof(struct sockaddr_in); char addr[16]; char rbuf[MAX_SIZE]; char sbuf[MAX_SIZE]="hello from server"; inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr); memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(10000); listenfd=socket(AF_INET,SOCK_STREAM,0); if(listenfd==-1) { perror("socket"); return -1; } err=bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(err==-1) { perror("bind"); return -1; } err=listen(listenfd,20); if(err==-1) { perror("listen"); return -1; } while(1) { connfd=accept(listenfd,(struct sockaddr*)&clientaddr,(socklen_t*)&addrlen); break; } n=recv(connfd,rbuf,MAX_SIZE,0); if(n==-1) { perror("recv"); return -1; } rbuf[n]='\0'; printf("%s\n",rbuf); n=send(connfd,sbuf,strlen(sbuf)+1,0); if(n==-1) { perror("send"); return -1; } close(connfd); close(listenfd); return 0; }
客户端程序:
# include <stdio.h> # include <string.h> # include <sys/socket.h> # include <arpa/inet.h> # define MAX_SIZE 256 int main() { int err; int sockfd,n; char rbuf[MAX_SIZE],sbuf[MAX_SIZE]="hello from client"; struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(10000); inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr); sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd==-1) { perror("socket"); return -1; } err=connect(sockfd,(struct sockaddr*)&servaddr,(socklen_t)sizeof(servaddr)); if(err<0) { perror("connect"); return -1; } n=send(sockfd,sbuf,strlen(sbuf)+1,0); if(n<0) { perror("send"); return -1; } n=recv(sockfd,rbuf,MAX_SIZE,0); if(n<0) { perror("recv"); return -1; } rbuf[n]='\0'; printf("%s\n",rbuf); close(sockfd); return 0; }
原文地址:http://blog.csdn.net/u011608357/article/details/28012573