原理图:
应用程序通过套接字通信,其协议如下:
TCP :服务器与客户端协议必须匹配,即都是用TCP 协议,先建立连接,再发送数据,其连接可靠。通信方式如下图所示:
TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议,由IETF的RFC 793定义。在简化的计算机网络OSI模型中,它完成第四层传输层所指定的功能,
tcp代码:
server.c
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include <unistd.h>
int startup(int _port,const char* _ip)
{
int sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0){
perror("socket");
exit(1);
}
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(_port);
local.sin_addr.s_addr=inet_addr(_ip);
socklen_t len=sizeof(local);
if(bind(sock,(struct sockaddr*)&local,len)<0){
perror("bind");
exit(2);
}
if(listen(sock,5)<0){
perror("listen");
exit(3);
}
return sock;
}
int main(int argc,char* argv[])
{
if(argc!=3){
printf("usage: %s [local_ip] [local_port]\n",argv[0]);
return 3;
}
int listen_sock=startup(atoi(argv[2]),argv[1]);
struct sockaddr_in remote;
socklen_t len=sizeof(struct sockaddr_in);
while(1){
int sock=accept(listen_sock,(struct sockaddr*)&remote,&len);
if(sock<0){
perror("accept");
continue;
}
printf("get a client,ip:%s,port:%d\n",inet_ntoa(remote.sin_addr),ntohs(remote.sin_port));
char buf[1024];
while(1){
ssize_t _s=read(sock,buf,sizeof(buf)-1);
if(_s>0){
buf[_s]=0;
printf("client#:%s\n",buf);
}else{
printf("client is quit!\n");
break;
}
}
close(sock);
}
return 0;
}
client.c
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include <unistd.h>
static void usage(const char* proc){
printf("usage: %s [ip] [port]\n",proc);
}
int main(int argc,char* argv[])
{
if(argc!=3){
usage(argv[0]);
return 3;
}
int sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0){
perror("socket");
return 1;
}
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
server.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0){
perror("connect");
return 2;
}
char buf[1024];
while(1){
printf("send#");
fflush(stdout);
ssize_t s=read(0,buf,sizeof(buf)-1);
buf[s-1]=0;
write(sock,buf,s);
}
close(sock);
return 0;
}
client.c
server.c
(这个简单的服务器只允许单进程访问)