//下边的代码是介绍同步socket的用法:
//需要用到的lib,可能不全,请看sdk的help自己添加
esock.lib
//需要的头文件,可能不全,请看sdk的help自己添加
#include <in_sock.h>
#include <nifman.h>
#include <Es_sock.h>
#if defined __WINS__
_LIT(KConnectIP,"192.168.0.1");//连接的ip地址,换成测试的ip
#else
_LIT(KConnectIP,"10.0.0.172");//移动的cmwap代理网关
#endif
const int KConnectPort = 80;//端口
HBufC8 *SocketGetUrl(TDesC8 &geturl);
void TestSocket()
{
_LIT8(KSendData, "POST http:://www.google.com.cn http/1.1\r\n\r\n");
TBuf8<128> sendData(KSendData);
HBufC8 *body = SocketGetUrl(sendData);
if(body)
{
//服务器端返回的数据处理
delete body;
}
}
HBufC8 *SocketGetUrl(TDesC8 &geturl)
{
RNif iNif;
RSocket iSocket;
TRequestStatus iStatus = KRequestPending;
TBuf8<512> writeBuf(geturl);
TBuf8<64> recvBuf;
HBufC8 *iBuffer = NULL;
iNif.Open();
{
RSocketServ iSocketServ;
User::LeaveIfError(iSocketServ.Connect());
TInetAddr iAddress;
if (iAddress.Input(KConnectIP) == KErrNone)
{
User::LeaveIfError(iSocket.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp));
iAddress.SetPort(KConnectPort);
iStatus = KRequestPending;
iSocket.Connect(iAddress, iStatus);
User::WaitForRequest(iStatus);
if (iStatus.Int() ==KErrNone)
{
iStatus = KRequestPending;
iSocket.Write(writeBuf,iStatus);
User::WaitForRequest(iStatus);
if (iStatus.Int() ==KErrNone)
{
TSockXfrLength iDummyLength;
TInt recvSize = 0;
for(;;)
{
iStatus = KRequestPending;
iSocket.RecvOneOrMore(recvBuf, 0, iStatus, iDummyLength);
User::WaitForRequest(iStatus);
if (iStatus.Int()==KErrNone)
{
recvSize += recvBuf.Length();
if(iBuffer==NULL)
iBuffer = HBufC8::NewL(recvSize);
else
iBuffer = iBuffer->ReAlloc(recvSize);
iBuffer->Des().Append(recvBuf);
}
else
{
break;
}
}
}
}
iSocket.Close();
}
iSocketServ.Close();
}
iNif.Close();
return iBuffer;
}
此段代码只是对socket用法的简单介绍,没有超时处理,如果要做超时处理的话,请自己添加。