套接字(-)

客户端

创建一个套接字

int socket(int domain,in type ,int protocol);

domin参数协议族(标准),type通信类型,protect指定使用饿协议

int sockfd=socket(AF_UNIX,SOCK_STEAM,0);

给套接字地址命名 (结构体类型)

stuctct sockadd_in

{

short int sin_family;

unsigned short int sin_short;

struct in_add sin_add;

}

struct in_addr

{

unsigned long int s_adddr;

}

struct sockaddr_in address;

address.sin_family=AF_UNIX(类型为ipv4)

address.sin_port=htons(6000); 服务器的端口号

adress.sin_addr.s_addr=inet_addr("127.0.0.1");//设置服务器的ip

int res=connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)) ;连接服务器

assert(res!=-1);
printf("input:\n");
while(1)
{
char buff[128]={0};
fgets(buff,128,stdin);
if(strncmp(buff,"end",3)==0)
{
break;
}
send(sockfd,buff,strlen(buff),0);
char recvbuff[128]={0};
int i=recv(sockfd,recvbuff,127,0);
printf("%s\n",recvbuff);
buff[0]=0;
}
close(sockfd);
return 0;
}

服务器端


#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
assert(sockfd!=-1);
struct sockaddr_in saddr,caddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(6000);
saddr.sin_addr.s_addr=inet_addr("127.0.0.1");
int res=bind(sockfd,(struct sockaddr *)&saddr,sizeof(saddr));
assert(res!=1);
listen(sockfd,5);
while(1)
{
int len=sizeof(caddr);
int c=accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c<0)
{
continue;
}
while(1)
{
char buff[128]={0};
int i=recv(c,buff,127,0);
if(i==0)
{
exit(0);
}
printf("%d\n",i);
printf("buff=%s\n",buff);
send(c,"ok",2,0);
}
close(c);
}
}






你可能感兴趣的:(套接字(-))