- //
- // HSocket.h
- // NetTest
- //
- // Created by Roy on 13-6-18.
- //
- //
- #ifndef __NetTest__HSocket__
- #define __NetTest__HSocket__
- #include "cocos2d.h"
- using namespace cocos2d;
- class HSocket{
- public:
- //用于连接服务器
- static int connect(const char* ip, unsigned short port);
- static int sendstr(char * str);
- static int getRecv();
- };
- #endif /* defined(__NetTest__HSocket__) */
- //
- // HSocket.cpp
- // NetTest
- //
- // Created by Roy on 13-6-18.
- //
- //
- #include "HSocket.h"
- #include <netdb.h>
- #include <iostream>
- #include <string.h>
- int socketHandle;
- using namespace std;
- int HSocket::connect(const char* ip, unsigned short port){
- struct sockaddr_in sa;
- struct hostent* hp;
- hp = gethostbyname(ip);
- if(!hp){
- return -1;
- }
- memset(&sa, 0, sizeof(sa));
- memcpy((char*)&sa.sin_addr, hp->h_addr, hp->h_length);
- sa.sin_family = hp->h_addrtype;
- sa.sin_port = htons(port);
- //请求连接服务器
- socketHandle = socket(sa.sin_family, SOCK_STREAM, 0);
- if(socketHandle < 0){
- printf( "failed to create socket\\n" );
- return -1;
- }
- int sd;
- if(sd = ::connect(socketHandle, (sockaddr*)&sa, sizeof(sa)) < 0){
- printf( "failed to connect socket\\n" );
- ::close(socketHandle);
- return -1;
- }
- CCLOG("连接服务器成功 ! IP: %s:%d --By Roy" ,ip,port);
- return 0;
- }
- struct Data{
- unsigned short flgs; //2
- unsigned short len; //2
- unsigned int no; //4
- char content;
- };
- int HSocket::sendstr(char * str)
- {
- int sd2;
- Data info;
- info.flgs = htons(127);
- info.len = htons(11);// 这里写死了,实际是 包头 8 (2+2+4)再加包身 x;
- info.no = htonl(10001);
- memcpy((void*)&info.content,str,strlen(str));
- cout << "sockethandler : " << socketHandle << endl;
- cout << str << endl;
- sd2 = send(socketHandle,(char*)&info,11,0);
- if (sd2 != -1)
- {
- cout << "send : " << sd2 << endl;
- }
- return 0;
- }
- int HSocket::getRecv()
- {
- while(1)
- {
- Data info;
- //先解包头,包头长度是 8 , 2 + 2 + 4
- recv(socketHandle, (Data*)&info, 8, 0);
- cout << "flags :" << ntohs(info.flgs) << endl;
- cout << "len : " << ntohs(info.len) << endl;
- cout << "no : " << ntohl(info.no) << endl;
- char content;
- //解包身
- recv(socketHandle, (char*)&content, ntohs(info.len),0);
- cout << "content : " << (char*)&(content) << endl;
- }
- return 0;
- }
- //调用
- HSocket * _socket = new HSocket();
- sd = _socket->connect("xx.xx.xx.xx", 8000);
- _socket->sendstr((char*)&"roy");
- cout << "socket rs : " << sd << endl;
- _socket->getRecv();
- //该片段来自于http://www.codesnippet.cn/detail/120320148996.html
来源: http://www.codesnippet.cn/detail/120320148996.html