求封装好的socket源代码,会拿来就用
求封装好的socket源代码,能拿来就用!
如题!主要是代码安全,网上找了一些不理想。自己不想写,估计也写不好。。。
------解决方案--------------------
厚重的ace,简单的boost
------解决方案--------------------
boost吧;
------解决方案--------------------
不知道有多少前人掉在TCP Socket
send(人多)send(病少)send(财富)
recv(人多病)recv(少财富)
陷阱里面啊!
http://topic.****.net/u/20120210/09/51109ed0-07b9-41f2-b487-a51597f2ca01.html
------解决方案--------------------
微软就有现成的
------解决方案--------------------
参考一下,刚写的.
如题!主要是代码安全,网上找了一些不理想。自己不想写,估计也写不好。。。
------解决方案--------------------
厚重的ace,简单的boost
------解决方案--------------------
boost吧;
------解决方案--------------------
不知道有多少前人掉在TCP Socket
send(人多)send(病少)send(财富)
recv(人多病)recv(少财富)
陷阱里面啊!
http://topic.****.net/u/20120210/09/51109ed0-07b9-41f2-b487-a51597f2ca01.html
------解决方案--------------------
微软就有现成的
------解决方案--------------------
参考一下,刚写的.
//16个字节的长度+ 数据
class Socket
{
public:
Socket(int s) : socket_(s) {}
~Socket()
{
close(socket_);
std::cerr << "bye" << std::endl;
}
private:
int socket_;
};
class SocketSender
{
public:
SocketSender(int socket) : socket_(socket), os_(&streambuf_)
{}
std::ostream& asStream()
{
return os_;
}
~SocketSender()
{
char* pbase = streambuf_.pbase(), *pptr = streambuf_.pptr();
if (pptr > pbase)
{
char buf[16];
sprintf(buf, "%15ld", pptr - pbase);
int nbyte, nbyteLeft = 16;
while (nbyteLeft > 0)
{
nbyte = send(socket_, buf + 16 - nbyteLeft, nbyteLeft, 0);
if (nbyte > 0)
{
nbyteLeft -= nbyte;
}
else if (-1 == nbyte)
{
throw std::runtime_error(strerror(errno));
}
}
nbyteLeft = pptr - pbase;
while (nbyteLeft > 0)
{
nbyte = send(socket_, pptr - nbyteLeft, nbyteLeft, 0);
if (nbyte > 0)
{
nbyteLeft -= nbyte;
}
else if (-1 == nbyte)
{
throw std::runtime_error(strerror(errno));
}
}
}
}
private:
int socket_;
class MyStreamBuf : public std::stringbuf
{
friend class SocketSender;
};
MyStreamBuf streambuf_;
std::ostream os_;
};
class SocketReceiver
{
public:
SocketReceiver(int socket) : socket_(socket), is_(&streambuf_)
{
char buf[16] = { 0 };
int nbyte = 0, nbyteLeft = 16;
while (nbyteLeft > 0)
{
nbyte = recv(socket_, buf + 16 - nbyteLeft, nbyteLeft, 0);
if (nbyte > 0)
{
nbyteLeft -= nbyte;
}
else if (nbyte == 0)
{
throw std::runtime_error("socket closed");
}
else if (nbyte == -1)
{
throw std::runtime_error(strerror(errno));
}
}
int len = 0;
if (sscanf(buf, "%d", &len) != 1
------解决方案--------------------
len < 0)
{
throw std::runtime_error("invalid length");
}
//std::cout << buf << ":" << len << std::endl;