client: socket --> connect -->send/recv-->close
server: sockket-->bind -->listen-->send/recv-->close
抄了都没看懂
//002.c
#include <func.h>
int main()
{
//client
int clientfd=socket(AF_INET,SOCK_STREAM,0);
if(clientfd<0){error(1,0,"socket");}//miao1
printf("client :%d\n",clientfd);
struct sockaddr_in serveraddr;
memset(&serveraddr,0,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(8080);
serveraddr.sin_addr.s_addr=inet_addr("192.168.235.128");
//sin_addr 你也是个结构体miao
int ret =connect(clientfd,(struct sockaddr*)&serveraddr,
sizeof(serveraddr));
if(ret==-1){error(1,errno,"connect");}
printf("connect sucess\n");
//进行数据的接收和发送
char buff[100]={0};//initialize
//默认情况虾,recv函数也是一个阻塞式函数
ret=recv(clientfd,buff,sizeof(buff),0);
printf("rec:%d bytes\n",ret);
printf("rec:%s \n",buff);
//发送数据
char msg[]="hello ,server";
ret=send(clientfd,msg,strlen(msg),0);
printf("send %d bytes.\n",ret);
while(1);
return 0;
}
//002sever.c
#include <func.h>
int main()
{
//创建server的监听套接字
int listenfd=socket(AF_INET,SOCK_STREAM,0);
if(listenfd==-1){error(1,-1,"listen");}
printf("listendfd=%d\n",listenfd);
//设置套接字的属性,网络地址可以重用(before bind)
int on=1;
int ret=setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
if(ret==-1){error(1,errno,"setsockopt");}
struct sockaddr_in serveraddr;
memset(&serveraddr,0,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(8080);
serveraddr.sin_addr.s_addr=inet_addr("192.168.235.128");
//human can see
printf("%s:%d\n",inet_ntoa(serveraddr.sin_addr),
ntohs(serveraddr.sin_port));
//bind 绑定一个套接字和一个网络地址
//只有服务器需要调用猫,暴露自己的网络地址
//lient会被操作系统自动分配一个
ret=bind(listenfd,(const struct sockaddr*)&serveraddr,
sizeof(serveraddr));
if(ret==-1){error(1,errno,"bind");}
//jianting client
ret=listen(listenfd,1);
printf("sever is listening.\n");
while(1){
struct sockaddr_in clientaddr;
memset(&clientaddr,0,sizeof(clientaddr));
socklen_t len=sizeof(clientaddr);
printf("len :%d\n",len);
//通过accpt的第二个参数可以获取到客户端的网络地址
int perrfd=accept(listenfd,
(struct sockaddr*)&clientaddr,&len);
//perrfd是listendfd的分身,主要用来和客户端交互
printf("peerfd:%d\n",perrfd);
printf("client addr:%s:%d\n",inet_ntoa(clientaddr.sin_addr),
ntohs(clientaddr.sin_port));
char buff[100]="hello.client";
//sizeof(buff)==len
//ret=send(perrfd,buff,strlen(buff),0);
//字符穿一般使用strlen
sleep(3);
ret=recv(perrfd,buff,strlen(buff),0);
printf("send %d bytes\n",ret);
memset(buff,0,sizeof(buff));//clean massage
ret=recv(perrfd,buff,sizeof(buff),0);
printf("recv: %s\n",buff);
}
//关闭套接字
close(listenfd);
return 0;
}
xiaohuichen@xiaohuichen-virtual-machine:~/001/710$ ./002sever
listendfd=3
192.168.235.128:8080
./002sever: bind: Address already in use
xiaohuichen@xiaohuichen-virtual-machine:~/001/710$ ./002
client :3
connect sucess神经,抄错了喵
改了还是一样喵