Cocos2dx网络学习笔记(一)
Cocos2dx网络学习笔记(一)学习资料C++ Socket 编程 简单的服务器直接上代码,再一一解释用到的东西 #include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
#define SOCKET int
#define ListenPort 9999
int main()
{
SOCKET st = socket( AF_INET,SOCK_STREAM,0 );
if ( st == -1 )
{
cout << "create socket failed" << endl;
return 0;
}
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons( ListenPort );
my_addr.sin_addr.s_addr = INADDR_ANY; /* inet_addr("127.0.0.1"); */
memset( my_addr.sin_zero,0,8 );
int result = ::bind( st,(struct sockaddr *) (&my_addr),sizeof(struct sockaddr) );
if ( result == -1 )
{
cout << "bind socket failed" << endl;
return 0;
}
result = listen( st,1 );
if ( result == -1 )
{
cout << "listen socket failed" << endl;
return 0;
}
struct sockaddr_in new_addr;
socklen_t sin_size = sizeof(struct sockaddr_in);
SOCKET new_connect = accept( st,(struct sockaddr *) (&new_addr),&sin_size );
if ( new_connect != -1 )
{
char* ip = inet_ntoa( new_addr.sin_addr );
cout << "new connect from " << ip << " with port:" << new_addr.sin_port << endl;
char buf[1024];
while ( true )
{
int recv_bytes = ::recv( new_connect,&buf,1024,0 );
if ( recv_bytes == -1 )
{
cout << "recv failed" << endl;
break;
}
cout << "receive from client:" << buf << endl;
string message = buf;
message = "this is reply for " + message;
int reply_len = message.length();
int send_bytes = ::send( new_connect,message.c_str(),reply_len,0 );
if ( send_bytes == -1 )
{
cout << "send failed" << endl;
break;
}
}
}
return 0;
}
简单的客户端
示例代码: #include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
#define SOCKET int
#define ListenPort 9999
using namespace std;
int main(int argc,char *argv[]) {
SOCKET st = socket( AF_INET,0 );
if ( st == -1 )
{
cout << "create socket failed" << endl;
return 0;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( ListenPort );
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");;
memset( server_addr.sin_zero,8 );
int result = connect(st,(struct sockaddr*)(&server_addr),sizeof(struct sockaddr));
if (result == -1)
{
cout << "connect server failed" << endl;
return 0;
}
string message;
while (true) {
cin >> message;
cout << "send to server:" << message << endl;
int reply_len = message.length();
int send_bytes = ::send( st,0 );
if ( send_bytes == -1 )
{
cout << "send failed" << endl;
break;
}
char buf[1024];
int recv_bytes = ::recv( st,0 );
if ( recv_bytes == -1 )
{
cout << "recv failed" << endl;
break;
}
cout << "receive from server:" << buf << endl;
}
return 0;
}
运行结果服务器 + telnet 服务器 + 客户端 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |