PageRenderTime 159ms CodeModel.GetById 150ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/c++/socket/socket.h

https://github.com/charlieyqin/development_misc
C++ Header | 99 lines | 44 code | 24 blank | 31 comment | 0 complexity | 55ae8ec487ce37d25ba26712069708e0 MD5 | raw file
 1/* 
 2   Socket.h
 3
 4   Copyright (C) RenĂŠ Nyffenegger
 5
 6   This source code is provided 'as-is', without any express or implied
 7   warranty. In no event will the author be held liable for any damages
 8   arising from the use of this software.
 9
10   Permission is granted to anyone to use this software for any purpose,
11   including commercial applications, and to alter it and redistribute it
12   freely, subject to the following restrictions:
13
14   1. The origin of this source code must not be misrepresented; you must not
15      claim that you wrote the original source code. If you use this source code
16      in a product, an acknowledgment in the product documentation would be
17      appreciated but is not required.
18
19   2. Altered source versions must be plainly marked as such, and must not be
20      misrepresented as being the original source code.
21
22   3. This notice may not be removed or altered from any source distribution.
23
24   RenĂŠ Nyffenegger rene.nyffenegger@adp-gmbh.ch
25*/
26
27#ifndef SOCKET_H
28#define SOCKET_H
29
30#include <WinSock2.h>
31
32#include <string>
33
34enum TypeSocket {BlockingSocket, NonBlockingSocket};
35
36class Socket {
37public:
38
39  virtual ~Socket();
40  Socket(const Socket&);
41  Socket& operator=(Socket&);
42
43  std::string ReceiveLine();
44  std::string ReceiveBytes();
45
46  void   Close();
47
48  // The parameter of SendLine is not a const reference
49  // because SendLine modifes the std::string passed.
50  void   SendLine (std::string);
51
52  // The parameter of SendBytes is a const reference
53  // because SendBytes does not modify the std::string passed 
54  // (in contrast to SendLine).
55  void   SendBytes(const std::string&);
56
57protected:
58  friend class SocketServer;
59  friend class SocketSelect;
60
61  Socket(SOCKET s);
62  Socket();
63
64
65  SOCKET s_;
66
67  int* refCounter_;
68
69private:
70  static void Start();
71  static void End();
72  static int  nofSockets_;
73};
74
75class SocketClient : public Socket {
76public:
77  SocketClient(const std::string& host, int port);
78};
79
80class SocketServer : public Socket {
81public:
82  SocketServer(int port, int connections, TypeSocket type=BlockingSocket);
83
84  Socket* Accept();
85};
86
87// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_2tiq.asp
88class SocketSelect {
89  public:
90    SocketSelect(Socket const * const s1, Socket const * const s2=NULL, TypeSocket type=BlockingSocket);
91
92    bool Readable(Socket const * const s);
93
94  private:
95    fd_set fds_;
96}; 
97
98
99#endif