socket.receive
的有关信息介绍如下:这可是我自己总结的,LZ不要误会哦~~!
1.简单服务器
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA sServer,sClient;
chat buf;
int retVal;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sServer)
{
WSACleanup();
return -1;//创建套接字失败
}
SOCKADDR_IN addrServ;
addrServ.sin_family=AF_INET;
addrServ.sin_port=htons(%%1);
addrServ.sin_addr.s_addr=INADDR_ANY;
retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN));
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//绑定套接字失败
}
retVal=listen(sServer,1);
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//开始监听失败
}
socketaddr_in addrClient;
int addrClientlen=sizeof(addrClient);
sClient=accept(sServer(sockaddr FAR*)&addrClient,&addClientlen);
if(INVALID_SOCKET==sClient)
{
closesocket(sServer);
WSACleanup();
return -1;//开始接受客户端连接失败
}
ZeroMemory(buf,sizeof(buf));
retVal=recv(sClient,buf,sizeof(buf));
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return -1;//接收数据失败
}
CString %%2(buf);
closesocket(sServer);
closesocket(sClient);
WSACleanup();
2.简单客户端
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA sHost;
SOCKADDR_IN addrServ;
chat buf;
int retVal;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sHost)
{
WSACleanup();
return -1;//创建套接字失败
}
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=inet_addr(%%1);
servAddr.sin_port=htons((short)%%2);
int nServAddlen=size(servAddr);
retVal=connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr));
if(sOCKET_ERROR==retVal)
closesocket(sHost);
WSACleanup();
return -1;//连接服务器失败
}
ZeroMemory(buf,sizeof(buf));
strcpy(buf,%%3);
retVal=send(sHost,buf,sizeof(buf),0);
if(SOCKET_ERROR==retVal)
{
closesocket(sHost);
WSACleanup();
return -1;//向服务器发送数据失败
}
closesocket(sHost);
WSACleanup();
3.获得本机IP
//#include
//#pragma comment(lib,"WS2_32.lib")
/*
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
*/
//#pragma comment(lib,"WS2_32.lib")
char szHostname,szHostaddress;
if(gethostname(szHostname,info(szHostname))!=SOCKET_ERROR)
{
HOSTENT *pHostEnt=gethostbyname(szHostname);
if(pHostEnt!=NULL){
sprintf(szHostaddress,"%d.%d.%d.%d",
( pHostEnt->h_addr_list&0x00ff ),
( pHostEnt->h_addr_list&0x00ff ),
( pHostEnt->h_addr_list&0x00ff ),
( pHostEnt->h_addr_list&0x00ff ));
}
}
else
return;
CString %%1(szHostaddress);
你好,用CSocket发数据的时候要注意两点,这也是我编程的经验,一个是不能用send发送带结构的数据,比如说class,struct等等;另外一个是发送的数据不能太大,譬如说2M。
结构传递需要引用吗?
以前自己写过1个FTP和HTTP的,也是SOCKET的
你试验下csrev.Send(TEF,300);看看,我只是好奇~
300改成sizeof(Sendj)