CPPSockets
CPPSockets 是一个 C++ 编写的网络类库,采用 Java 的类命名方式和接口,仿造了一个 C++版本的,比如ServerSocket DatagramSocket SocketAddress
起因是c++封装的socket 多如牛毛,但各有各的命名风格,而且有的水平参差不齐,不甚满意,长久以来就想寻找一个完美的答案,近日又用了java socket,发觉它的命名规范封装架构,非常不错,使用起来也比较方便,多种构造其他方法来使用类。于是操刀写代码,把c++的socket封装成java.net下的一些类。
You can get the source code from my home page:
http://code.qtuba.com/studio/CPPSockets.html or git https://github.com/344717871/CPPSockets
下面先来看个udp 例子。
try {
// udp socket绑定444端口 / udp socket bind on 444 port
DatagramSocket u(444);
//发送给目标444端口 / sendto target 444 port
std::string s1="hello myself!";
DatagramPacket spk( s1.c_str(),s1.length() , SocketAddress("127.0.0.1",444) ); //数据buff,数据长度,sa目标地址
u.send(spk);
while (1)
{
//接收 / receive udp Packet
DatagramPacket pk ;
u.receive(pk);
printf("recv len[%d] %s \n",pk.getLength(),pk.getData());
//Sleep(1);
// echo self
DatagramPacket spk( pk.getData(), pk.getLength(), pk.getSocketAddress() );
u.send(spk);
}
}
catch (exception e)
{
printf("err %s",e.what());
}
下面是tcp http server例子。运行后打开浏览器即可看到输出.
#include "serversocket.h"
#include <sstream>
DWORD WINAPI clientthread(LPVOID l)
{
Socket b=*(Socket*)l;
std::stringstream content;
content<<"hello, CPPSockets!<br> Java Naming style Sockets Classes";
{
std::stringstream Response;
Response << "HTTP/1.1 " << 200 <<"\r\n" ;
Response << "Content-Type: text/html;charset=gb2312\r\n";
if(content.str().length()>0)
Response<< "Content-Length: " << content.str().length() << "\r\n";
Response<< "Connection: close\n\n";
b.getOutputStream().write( (char*)Response.str().c_str() ,Response.str().length() );
if(content.str().length()>0)
b.getOutputStream().write( (char*)content.str().c_str() ,content.str().length() );
}
while ( 1 )
{
try
{
printf("%c", b.getInputStream().readByte() );
//b.close();
}catch(...)
{
printf("recv err [%d] \n",b.GetSock());
b.close();
break;
}
}
printf("close [%d] \n",b.GetSock());
return 0;
}
//-------------------------------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
try
{
//You can use the browser ( IE, Firefox, etc. ) to visit:
//http://127.0.0.1/
// simple http server
ServerSocket s(80);
//or
//ServerSocket s;
//s.bind( SocketAddress("0.0.0.0",80));
printf("listen ok\n");
Socket c2("127.0.0.1",80);
while(1)
{
Socket c = s.accept ();
printf(" Accept [%d]\n",c.GetSock() );
CloseHandle( CreateThread(0,0,clientthread,&c,0,0) );//fixme
}
}catch(exception e){
printf("%s",e.what());
}
}