forked from chunyi1994/cppevent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.h
63 lines (54 loc) · 1.22 KB
/
socket.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef SOCKET_H
#define SOCKET_H
#include <sys/socket.h>
#include <unistd.h>
#include <assert.h>
#include <memory>
#include <fcntl.h>
namespace cppevent{
//RAII的Sockst类, 会在析构时关闭fd
class Socket
{
public:
//typedef std::shared_ptr<sockets::InetAddress> AddressPtr;
Socket(int fd = -1);
~Socket();
void setFd(int fd);
int fd() const;
private:
int fd_;
};
//把用于socket设置为非阻塞方式
static void setnonblocking(int sockfd) {
int opts;
opts = fcntl(sockfd, F_GETFL);
if (opts < 0) {
perror("fcntl(sock, GETFL)");
return;
}
opts = opts | O_NONBLOCK;
if (fcntl(sockfd, F_SETFL, opts) < 0) {
perror("fcntl(sock,SETFL,opts)");
return;
}
}
/*
static int createSocket(){
int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
//assert(socket > 0);
return sockfd;
}*/
static int createNonBlockingSocket(){
int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
//assert(socket > 0);
setnonblocking(sockfd);
return sockfd;
}
/*
static int createNonBlockingSocket(){
int sockfd = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
//assert(sockfd > 0);
return sockfd;
}*/
}
#endif // SOCKET_H