目录
客户端
#include<iostream>
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
using namespace std;
int main()
{
//创建socket
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
perror("socket error");
exit(-1);
}
struct sockaddr_in seraddr;
inet_pton(AF_INET, "192.168.76.128", &seraddr.sin_addr.s_addr); //或 127.0.0.1
seraddr.sin_family = AF_INET;
seraddr.sin_addr.s_addr = INADDR_ANY;
seraddr.sin_port = htons(9999);
//连接服务器
int ret = connect(fd, (struct sockaddr*)&seraddr, sizeof(seraddr));
if (ret == -1)
{
perror("connect error");
exit(-1);
}
int num = 0;
while (1)
{
char sendBuf[1024] = { 0 };
//fgets(sendBuf, sizeof(sendBuf), stdin);
sprintf(sendBuf, "send data :%d", num++);
//sprintf(sendBuf, "send data :", num++);
write(fd, sendBuf, strlen(sendBuf) + 1);
//接收
int len = read(fd, sendBuf, sizeof(sendBuf));
if (len == -1)
{
perror("read error");
exit(-1);
}
else if (len > 0)
{
cout << "read buf =" << sendBuf << endl;
}
else
{
cout << "服务器已经断开连接..." << endl;
break;
}
sleep(1);
}
close(fd);
return 0;
}
服务器
#include<iostream>
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#include<time.h>
#include<sys/select.h>
using namespace std;
int main()
{
//创建socket
int lfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(9999); //主机字节序转网络字节序
//bind 绑定
int ret = bind(lfd, (struct sockaddr*)&saddr, sizeof(saddr));
if (ret == -1)
{
perror("bind error");
exit(-1);
}
//监听
listen(lfd, 8);
//创建一个 fd_set 的集合,存放的是需要检测的文件描述符
fd_set rdset,temp;
FD_ZERO(&rdset); //FD_ZERO 的参数是指针类型,需要传递地址进去
FD_SET(lfd, &rdset);
int maxfd = lfd;
while (1)
{
temp = rdset;
//调用 select 系统函数,让内核帮检测哪些文件描述符有数据
int rett =select(maxfd + 1, &temp, NULL, NULL, NULL);
if (rett == -1)
{
perror("select error");
exit(-1);
}
else if (rett == 0) //rett == 0,就是超时时间到了也没检测到,\
这里是没用的,因为在 select 函数中超时时间设置为永久阻塞了
{
continue;
}
else if (rett > 0)
{
//说明检测到了有文件描述符的对应的缓冲区的数据发生了变化
if (FD_ISSET(lfd, &temp))
{
//表示有新的文件描述符连接进来
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
int cfd = accept(lfd,(struct sockaddr*)&cliaddr, &len);
//将最新的文件描述符加入到集合中
FD_SET(cfd, &rdset);
//更新最大的文件描述符
maxfd = maxfd > cfd ? maxfd : cfd;
}
for (int i = lfd + 1; i <= maxfd; ++i)
{
if (FD_ISSET(i, &temp))
{
//说明这个文件描述符对应的客户端发来了数据
char buf[1024] = { 0 };
int len = read(i, buf, sizeof(buf));
if (len == -1)
{
perror("read error");
exit(-1);
}
else if (len > 0)
{
cout << "read data :" << buf << endl;
write(i, buf, strlen(buf) + 1);
}
else if (len == 0)
{
cout << "client close...(客户端断开连接)" << endl;
close(i);
FD_CLR(i, &rdset);
}
}
}
}
}
close(lfd);
return 0;
}