记录简单用例:
server 头文件:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <unistd.h>
class ServerNet
{
public:
ServerNet();
~ServerNet();
bool socketInit(int port);
bool dostart();
void exit();
private:
bool isloop;
struct sockaddr_in local_addr;
int sock_fd;
};
cpp文件
#include "selectudp.h"
#include <cstring>
#include <iostream>
#define BUFFERSIZE 2048
ServerNet::ServerNet()
{
}
ServerNet::~ServerNet()
{
}
bool ServerNet::socketInit(int port)
{
//初始化udp
sock_fd = -1;
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0)
{
std::cout << "socket init err" << std::endl;
return false;
}
do
{
// 设置本地端口信息
memset(&local_addr, 0, sizeof(local_addr));
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = INADDR_ANY;//inet_addr("127.0.0.1");//
local_addr.sin_port = htons(port);
// bind端口
int ret = bind(sock_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
if (ret != 0)
{
std::cout << "socket bind failed" << std::endl;
break;
}
// // 设置超时
// struct timeval tv;
// tv.tv_sec = 1;
// tv.tv_usec = 0;
// if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) != 0)
// {
// std::cout << "socket setovertime failed" << std::endl;
// break;
// }
//成功
return true;
} while (0);
//失败
close(sock_fd);
return false;
}
//数据处理接收
bool ServerNet::dostart()
{
char buf[BUFFERSIZE]={0};
struct sockaddr_in remote_addr;
socklen_t remote_len = sizeof(remote_addr);
isloop = true;
fd_set read_fds;
struct timeval tv;
while(isloop)
{
//使用select io复用
FD_ZERO(&read_fds);
FD_SET(sock_fd, &read_fds);
//每次都会重置
tv.tv_sec = 1;
tv.tv_usec = 0;
int num = select(sock_fd+1, &read_fds, NULL, NULL, &tv);
if (num <= 0)
{
std::cout<<"select no fd"<<std::endl;
continue;
}
//非目标文件描述符
if (!FD_ISSET(sock_fd, &read_fds))
{
std::cout<<"not active fd"<<std::endl;
continue;
}
//读取数据--阻塞
int length = recvfrom(sock_fd,buf,BUFFERSIZE-1,0,(struct sockaddr*)&remote_addr,&remote_len);
if (length < 0 )
{
std::cout<<"recv length = -1"<<std::endl;
continue;
}
std::string remoteip = inet_ntoa(remote_addr.sin_addr);
std::cout<<"recv from "<<remoteip<<" length= "<< length <<std::endl;
//to do
memset(buf,0,BUFFERSIZE);
}
close(sock_fd);
return false;
}
//退出循环
void ServerNet::exit()
{
isloop = false;
return;
}
client 文件:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <iostream>
using namespace std;
int main() {
int port = 15006;
int sockfd;
struct sockaddr_in addr;
char send_buf[] = "i am send.";
int send_num = 0;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
while (1) {
sleep(3);
send_num = sendto(sockfd, (char*)send_buf, (size_t) sizeof(send_buf), 0, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));
cout<<"send bytes: "<<send_num<<" send messages: "<<send_buf<<endl;
}
return 0;
}