#include
#define SEVIP "192.168.0.116"
#define SEVPORT 6669
#define CLISIZE 5
typedef struct sockaddr_in socketadd;
int main(int argc, const char *argv[])
{
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1)
{
perror("socket");
return -1;
}
in_addr_t port_t = htons(SEVPORT);
in_addr_t ip_t = inet_addr(SEVIP);
socketadd a = {
.sin_family = AF_INET,
.sin_port = port_t,
.sin_addr.s_addr = ip_t };
//将套接字与主机ip和端口号绑定
if(bind(oldfd,(struct sockaddr*)&a,sizeof(a))==-1)
{
perror("bind");
return -1;
}
//把旧的标识符用于监听客户端队列
if(listen(oldfd,CLISIZE)==-1)
{
perror("listen");
return -1;
}
socketadd cln;
int clnlen = sizeof(cln);
//接收客户端队列信息生成新的标识符用于与客户端通信
int newfd=accept(oldfd,(struct sockaddr*)&cln,&clnlen);
if(newfd == -1)
{
perror("accept");
return -1;
}
char buff[1024]="";//创建通信用的缓冲区
while(1)
{
memset(buff,0,sizeof(buff));//每次接收之前清空缓存区
int len =recv(newfd,buff,sizeof(buff),0);//阻塞接收
if(len == 0)
{
printf("客户端断开链接");
break;
}
printf("收到了客户端的信息:%s",buff);
strcat(buff,"666");
send(newfd,buff,sizeof(buff),0);
memset(buff,0,sizeof(buff));
}
return 0;
}
#include
#define SEVIP "192.168.0.116"
#define SEVPORT 6669
typedef struct sockaddr_in socketadd;
int main(int argc, const char *argv[])
{
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1)
{
perror("socket");
return -1;
}
in_addr_t port_t = htons(SEVPORT);
in_addr_t ip_t = inet_addr(SEVIP);
socketadd cln = {
.sin_family = AF_INET,
.sin_port = port_t,
.sin_addr.s_addr = ip_t
};
if(connect(oldfd,(struct sockaddr*)&cln,sizeof(cln))==-1)
{
perror("connect");
return -1;
}
char buff[1024]="";
while(1)
{
printf("客户端发送给服务端:");
fgets(buff,sizeof(buff),stdin);
send(oldfd,buff,sizeof(buff),0);
memset(buff,0,sizeof(buff));
recv(oldfd,buff,sizeof(buff),0);
printf("收到了服务端的信息:%s",buff);
}
return 0;
}