可以将客户端的逻辑设计成:
1.将username,password 封装进buffer
2.连接服务端
3.发送buffer
4.接收二进制的系统当前时间
5.显示时间
代码如下:
服务端地址设置部分:
[cpp] view plain copy print?
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons( port );
addr_server.sin_addr.s_addr = inet_addr( ip );
创建连接:
sock_client = socket( AF_INET, SOCK_STREAM, 0 );
连接服务端代码:
flag = connect( sock_client, ( struct sockaddr* ) &addr_server, sizeof( addr_server ) );
设置buffer填充username/password代码:
sprintf(buffer, "%s", "username");
sprintf(buffer + 32, "%s", "password" );
buffer[31]=buffer[63] = 0;
接着是发送
flag = send( sock_client, buffer, 64, 0 );
if( flag == 64 )
{
printf( "send ok\n");
}
接收部分代码:
flag = recv( sock_client, buffer, 64, 0 );
if( flag != sizeof( time_t ) )
{
printf( "recv does not follow protocal\n");
close( sock_client );
continue;
}
将接收到的二进制数据转成时间
memcpy( curtime, buffer, sizeof( time_t ) );
struct tm *ptm = localtime( curtime );
显示时间:
printf( "system time:%04d-%02d-%02d-%02d:%02d:%02d\n", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, ptm->tm_sec );
关闭连接:
printf( "ok,now we close connection\n" );
close( sock_client );
实际开发中,为了追求并发效率和提升搞压效果,客户端需要有一个循环,另外可以多进程同时操作。