1.典型的CS模型流程图
2.服务端需要做的事情
(1)socket()
:建立服务端套接字;
(2)bind()
:绑定IP和端口号,初始化struct sockaddr_in addr
;
(3)listen()
:指定最大同时发起连接数;
(4)accept()
:阻塞等待客户端发起连接;
(5)read()
:读取客户端数据;
(6)对已读取的数据进行处理;
(7)write()
:写回客户端;
(8)close()
3.客户端需要做的事情
(1)socket()
:建立客户端套接字;
(2)bind()
:当进行“隐式绑定”时,不需要第二步;
(3)connect()
:发起连接;
(4)write()
:向服务器写数据;
(5)read()
:读取服务器端的数据;
(6)close()
4.服务器端实例
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<ctype.h>
#include<arpa/inet.h>
#define SERV_IP "127.0.0.1"
#define SERV_PORT 6666
int main()
{
int lfd,cfd;
struct sockaddr_in serv_addr,clie_addr;
socklen_t clie_addr_len;
char buf[BUFSIZ];
int n;
lfd = socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(lfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
listen(lfd,128);
clie_addr_len = sizeof(clie_addr);
cfd = accept(lfd,(struct sockaddr *)&clie_addr,&clie_addr_len);
while(1){
n = read(cfd,buf,sizeof(buf));
for(int i=0;i<n;i++){
buf[i] = toupper(buf[i]);
}
write(cfd,buf,n);
}
close(lfd);
close(cfd);
return 0;
}
连接命令:nc 192.168.0.2 6666