/*
	CMySocket
	Socket処理を行う

	Version		: 0.0 (Release1)

	作成日		: 2002/05/25
	修正日		: ----/--/--
	改定履歴	: 
*/

#if !defined(AFX_MYSOCKET_H__7F95F7C3_A7E3_42B5_9FE2_390923A96E48__INCLUDED_)
#define AFX_MYSOCKET_H__7F95F7C3_A7E3_42B5_9FE2_390923A96E48__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <WinSock2.h>
#include "TimeOut.h"
#include "IPAddress.h"

#define	ErrorReturn(str,code) \
{\
	m_lastErrorString = str;\
	Close();\
	return(code);\
}\

class CFastListener;
class CMySocket : public CTimeOut
{
public:
	//	ソケットタイプ
	virtual int IsSSL() {return 0;};

	//	タイムアウト
	virtual void OnTimeOut();
	void SetTimeOutTick(int timeOut);

	//	接続・切断
	virtual void Close();
	virtual int Connect(CString server,int port);
	virtual int SetHandle(SOCKET socket);

	//	送信・受信
	int Send(char *data,int len);
	int SendString(CString str);
	int Recv(char *data,int len);
	int RecvString(CString &str,int recvLen=0);
	int Peek(char *data,int len);
	int PeekString(CString &str);

	//	接続受付
	virtual int Accept(CMySocket &recv,int blocking=FALSE);
	virtual int Listen(int port=0);

	//	ステータス
	static CIPAddress GetLocalhost();
	int GetInRecvBuf();
	int IsDisconnect();
	int IsDisconnectAndNodata();
	int IsError();
	int CanWrite(int timeOut=0);
	virtual int CanRecv(int timeOut=0);

	//	情報
	CIPAddress GetAddres();
	CIPAddress GetPeerAddres();
	int GetPeerPort();
	int GetPort();
	WSADATA * GetWinsockInfo();
	CString	GetLastErrorString() {return(m_lastErrorString);};

	//	バッファ
	int RecvToPeekBuf();
	int PeekBufIsFull();
	int InPeekBuf();

	CMySocket();
	CMySocket(CMySocket &other) {ASSERT(0);};	//	コピー不可
	virtual ~CMySocket();


protected:
	virtual int RecvDataPending(int timeOut=0);
	virtual int _send(SOCKET s,char *buf,int len,int flags);
	virtual int _recv(SOCKET s,char *buf,int len,int flags);
	virtual int Create();
	virtual int Bind(int port);

	int GetPeekBufLeft();
	int PeekPeekBuf(char *buf,int len);
	int GetPeekBuf(char *data,int len);
	void AddPeekBuf(char *data,int len);

	SOCKET		m_socket;
	int			m_connect;
	CString		m_lastErrorString;
	char		*m_stringBuf;
	char		*m_peekBuf;
	int			m_peekBufUsed;
	int			m_disconnect;
	int			m_timeoutTick;
	
	int InitApi();
};

#endif // !defined(AFX_MYSOCKET_H__7F95F7C3_A7E3_42B5_9FE2_390923A96E48__INCLUDED_)
