00001 #ifndef WINCMP_SOCKSTR_H
00002 #define WINCMP_SOCKSTR_H
00003 #include "WBWin.h"
00004 #include <winsock2.h>
00005 #include <Base/StrBufBase.h>
00006
00007 namespace Spr {;
00008
00009
00010 class WBSockStream;
00011
00012 class SPR_DLL WBSockStreambuf:public UTStreambufBase{
00013 friend WBSockStream;
00014 protected:
00015 SOCKET sock;
00016 SOCKET sockListen;
00017 UINT port;
00018 SOCKADDR_IN oppAdr;
00019 int lastError;
00020 const char* lastErrorStr;
00021 bool bConnected;
00022 bool bListening;
00023 bool bServer;
00024 WSAEVENT closeEvent;
00025 public:
00026
00027 WBSockStreambuf(char* gb, int gl, char* pb, int pl);
00028
00029 BCC_CDECL ~WBSockStreambuf();
00030
00031 bool IsConnected();
00032
00033 bool IsListening(){return bListening;}
00034
00035 bool IsServer(){return bServer;}
00036
00037 bool Listen(UINT port);
00038
00039 bool Accept(bool bBlock);
00040
00041 bool Connect(const char* adr, UINT port);
00042
00043 void Close();
00044 protected:
00045 UINT read(void* buf, UINT bufLen);
00046 UINT write(void* buf, UINT bufLen);
00047 virtual int in_avail_stream();
00048 const char* ErrorMessage();
00049 const char* ErrorNumToMessage(int errorNum);
00050 void GetError();
00051 int AddSockRef();
00052 int ReleaseSockRef();
00053 static int sockRefCount;
00054 };
00055
00056
00057 class SPR_DLL WBSockStream:public std::iostream{
00058 protected:
00059 WBSockStreambuf buf;
00060 enum{BUFFERLEN = 1000};
00061 char getBuffer[BUFFERLEN];
00062 char putBuffer[BUFFERLEN];
00063 public:
00064 WBSockStream();
00065 BCC_CDECL ~WBSockStream();
00066
00067 const char* ErrorMessage(){ return buf.ErrorMessage(); }
00068
00069 bool connect(const char* addr, UINT port){ return Connect(addr, port); }
00070 bool Connect(const char* addr, UINT port){
00071 bool rv = buf.Connect(addr, port);
00072 if (rv) clear();
00073 return rv;
00074 }
00075
00076 bool listen(UINT port){ return Listen(port); }
00077 bool Listen(UINT port){ return buf.Listen(port); }
00078
00079 bool accept(bool bBlock = false){ return Accept(bBlock); }
00080 bool Accept(bool bBlock = false){
00081 bool rv = buf.Accept(bBlock);
00082 if (rv) clear();
00083 return rv;
00084 }
00085
00086 bool IsConnected(){ return buf.IsConnected(); }
00087
00088 bool IsListening(){ return buf.IsListening(); }
00089
00090 int avail(){ return Avail(); }
00091 int Avail(){ return buf.in_avail() + buf.in_avail_stream(); }
00092
00093 void close(){ Close(); }
00094 void Close(){ buf.Close(); clear(std::ios::badbit); }
00095 };
00096 }
00097 #endif