PageRenderTime 215ms CodeModel.GetById 163ms app.highlight 5ms RepoModel.GetById 44ms app.codeStats 0ms

/Socket.h

https://github.com/chaoswork/httpServer
C++ Header | 76 lines | 49 code | 15 blank | 12 comment | 0 complexity | 795d623273c2388c4f2fd3e64a701f9e MD5 | raw file
 1#ifndef  SOCKET_H
 2#define  SOCKET_H
 3
 4#ifndef	PACKAGE_H
 5#include    "package.h"
 6#endif
 7
 8
 9#include  <string>
10#include  <string.h>
11
12
13#ifdef linux
14#include  <sys/socket.h>
15#include  <netinet/in.h>
16#include  <arpa/inet.h>
17#include  <netdb.h>
18#include  <sys/types.h>
19#include  <unistd.h>
20typedef	int SOCKET;
21typedef void* optval_t;
22#else //WIN32
23#include  <winsock2.h>
24#include  <Ws2tcpip.h>
25#pragma comment(lib,"WS2_32.lib")
26//typedef unsigned int socklen_t;
27typedef const char* optval_t;
28#endif
29
30
31#ifndef ERROR_H
32#include    "error.h"
33#endif
34#include    "SocketStream.h"
35
36
37CW_BEGIN
38
39
40
41
42
43using std::string;
44/* Socket is class to handle socket,can't copy publicly.
45 * With the action connect,close,and server action bind,
46 * listen and accept.
47 * I tried to make it Exception safety and thread safe and
48 * cross linux and windows platform.*/
49class Socket{
50public:
51	explicit Socket(SOCKET sk=-1);
52	Socket(int af,int type,int protocol=0);
53	virtual	~Socket();
54	void connect(const string& ipAddr,unsigned short port);
55	/* bind,listen and accept should used for server*/
56	void bind(unsigned short port);
57	void listen(int backlog);
58	//Socket accept(struct sockaddr_in* cliAddr=0);
59	void accept(Socket& SK,struct sockaddr_in* cliAddr=0);
60	void close();
61
62	/* Socket i/o stream */
63	SocketStream getSocketStream();
64protected:
65	void create(int af,int type,int protocol=0);
66	/* accept return a Socket Object,so we make the copy constructor
67	 * as private,and also disallow the operator= used public*/
68	Socket(const Socket& SK){m_socket=SK.m_socket;}
69	Socket& operator=(const Socket&);
70private:
71	//SOCKET m_socket;
72	int m_socket;
73	bool socketClosed;
74};
75CW_END
76#endif  /*SOCKET_H*/