netsocket.h

来自「linux下的线程池,其中使用了条件变量,互斥锁等保持线程同步的变量!」· C头文件 代码 · 共 103 行

H
103
字号
#if !defined _NETSOCKET_H_INCLUDE_
#define _NETSOCKET_H_INCLUDE_
#include "platform.h"

#ifdef WIN32
	/*
	for windows
	*/
	#include <winsock.h>
	#define GETERROR			WSAGetLastError()
	#define CLOSESOCKET(s)		closesocket(s)
	#define IOCTLSOCKET(s,c,a)  ioctlsocket(s,c,a)
	#define CONN_INPRROGRESS	WSAEWOULDBLOCK
	typedef int socklen_t;
#else
	/*
	for linux
	*/
	#include <sys/time.h>
	#include <stddef.h>
	#include <unistd.h>
	#include <stdlib.h>
	#include <sys/wait.h>
	typedef int            BOOL;
	typedef unsigned char  BYTE;
	typedef unsigned short WORD;
	typedef unsigned int   DWORD;
	#define TRUE  1
	#define FALSE 0

	/*
	for socket
	*/
	#include <sys/socket.h>
	#include <netinet/in.h>
	#include <unistd.h>
	#include <sys/ioctl.h>
	#include <netdb.h>
	#include <sys/errno.h>
	#include <arpa/inet.h>

	typedef int SOCKET;
	typedef sockaddr_in			SOCKADDR_IN;
	typedef sockaddr			SOCKADDR;
	#define INVALID_SOCKET	    (-1)
	#define SOCKET_ERROR        (-1)
	#define GETERROR			errno
	#define WSAEWOULDBLOCK		EWOULDBLOCK
	#define CLOSESOCKET(s)		close(s)
	#define IOCTLSOCKET(s,c,a)  ioctl(s,c,a)
	#define CONN_INPRROGRESS	EINPROGRESS
#endif

const int PROTOCOL_UDP	=	1;
const int PROTOCOL_TCP	=	2;

class NetSocket
{
public:
	NetSocket();
	virtual ~NetSocket();
	bool Attach(SOCKET socket);
	bool Close();
	bool Connect(char *szAddr,int port,unsigned long ip = 0);
	bool Listen();
	bool Initialize(int protocol);
	
	int Recv(char *buf,int len);
	int Send(char *buf,int len);
	int RecvFrom(char *buf,int len,SOCKADDR_IN *addr,int *addrlen);
	int SendTo(char *buf,int len,SOCKADDR_IN *addr);

	bool CanWrite();
	bool CanRead();
	bool HasExcept();

	bool SetNonBlocking();
	bool SetAsync();
	bool BindAddr(char *ip,int port);
	void Reset();

	bool SetSendBufferSize(int len);
	bool SetRecvBufferSize(int len);
	bool SetReuseAddr(bool reuse);

	bool GetLocalAddr (char *addr, short *port,unsigned long *ip = NULL);
	bool GetRemoteAddr(char *addr,short *port,unsigned long *ip = NULL);
	
	SOCKET Accept();
	unsigned long   GetMaxCanReadSize();
	SOCKET FromHandle();

private:
	bool _NetStartUp(int VersionHigh,int VersionLow);
	bool _NetCleanUp();

	SOCKET		m_socket;
	static int	m_nCount;
	bool        m_bNonBlocking;
};

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?