![](https://i-blog.csdnimg.cn/blog_migrate/0858a2e402e7498a14f2f3ec85d371d5.png)
![](https://i-blog.csdnimg.cn/blog_migrate/d33eb8e7b55bce30a2146e8786670bce.png)
#include<myhead.h>
#define PORT 8888
#define IP "192.168.116.169"
int main(int argc, const char *argv[])
{
//定义一个套接字
int sfd =-1;
if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket error");
return -1;
}
printf("sfd=%d\n",sfd);
//创建结构体绑定IP和端口号
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
if((bind(sfd,(struct sockaddr*)&sin,sizeof(sin)))==-1)
{
perror("bind error");
return -1;
}
printf("绑定成功\n");
//设置监听状态
if(listen(sfd,128)==-1)
{
perror("listen error");
return -1;
}
printf("监听模式\n");
//定义容器接受客户端地址信息
struct sockaddr_in cin;
//定义客户端容器的大小
socklen_t socklen=sizeof(cin);
//再定义一个套接字用于通信
int newfd=-1;
if(newfd=(accept(sfd,(struct sockaddr *)&cin,&socklen))==-1)
{
perror("accept error");
return -1;
}
printf("newfd=%d\n",newfd);
puts("#####");
//进行通信
char buf[128]="";
while(1)
{
//清空数组
bzero(buf,sizeof(buf));
//读取客户端传来的数据
int res = recv(newfd,buf,sizeof(buf),0);
if(res==0)
{
printf("客户端断开连接\n");
break;
}
printf("[%s:%d]:%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf);
//给客户端发送消息
/* strcat(buf,"**");
send(newfd,buf,sizeof(buf),0);
printf("发送成功\n");
*/
}
close(newfd);
close(sfd);
return 0;
}
#include<myhead.h>
#define USRIP "192.168.116.169"
#define USRPORT 6666
#define SERIP "192.168.116.169"
#define SERPORT 8888
int main(int argc, const char *argv[])
{
//创建套接字文件
int cfd = -1;
if((cfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket error");
return -1;
}
//绑定
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(USRPORT);
sin.sin_addr.s_addr = inet_addr(USRIP);
if(bind(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("bind error");
return -1;
}
printf("bind success\n");
//定义结构体存储服务器信息
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(SERPORT);
cin.sin_addr.s_addr = inet_addr(SERIP);
socklen_t socklen = sizeof(cin);
//连接服务器
if(connect(cfd,(struct sockaddr*)&cin,socklen)==-1)
{
perror("connect,error");
return -1;
}
printf("connect success\n");
//向服务器发送数据
char buf[128]="";
while(1)
{
//清空数组
bzero(buf,sizeof(buf));
//终端输入
fgets(buf,sizeof(buf),stdin);
//将输入的字符串'\n'换成'\0'
buf[strlen(buf)-1]=='\0';
//发送输入的数据到服务器
send(cfd,buf,sizeof(buf),0);
printf("发送成功\n");
//退出条件
if(strcmp(buf,"quit")==0)
{
printf("退出连接\n");
break;
}
// recv(sfd,buf,sizeof(buf),0);
// printf("***:%s\n",buf);
puts("**********\n");
}
close(cfd);
return 0;
}