网络编程课上的第一个小实验。客户端发送命令“gettime”到服务器,服务器获取本地时间并发送回客户端。就是这么简单。。。
不多说了直接上代码。
// 时间同步客户端.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib,"wsock32.lib")
#define MAXSIZE 100
int getline(char* s,int max);
int _tmain(int argc, _TCHAR* argv[])
{
//初始化WinSock
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2),&wsaData);
if(ret != 0)
{
printf("WSAStratup() failed!code:%d\n",WSAGetLastError());
return -1;
}
if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wVersion)!=2)
{
WSACleanup();
printf("Invaild WinSock Version\n");
return -1;
}
//建立客户端套接字
SOCKET sockclient;
sockclient = socket(AF_INET,SOCK_STREAM,0);
if(sockclient==INVALID_SOCKET)
{
WSACleanup();
printf("socket() failed!code:%d\n",WSAGetLastError());
return -1;
}
//服务器地址信息
struct sockaddr_in saServer;
saServer.sin_family = AF_INET;
saServer.sin_port=htons(6000);
saServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//连接服务器
ret = connect(sockclient,(sockaddr*)&saServer,sizeof(saServer));
if(ret == SOCKET_ERROR)
{
printf("connect() failed!code:%d\n",WSAGetLastError());
closesocket(sockclient);
WSACleanup();
return -1;
}
else
printf("please input 'gettime' to get system time\n");
//向服务器发送请求
char buff[MAXSIZE];
char t[MAXSIZE];
memset(buff,0,MAXSIZE);
while(strcmp(buff,"quit")!=0)
{
getline(buff,MAXSIZE);
if (strcmp(buff,"gettime"))
{
printf("unkonw command:%s\n", buff);
continue;
}
if(send(sockclient,buff, sizeof(buff), 0) <= 0) {
printf("send failed !\n");
closesocket(sockclient);
WSACleanup();
return -1;
}
if(recv(sockclient,t, sizeof(t), 0) <= 0)
{
printf("recv() failed!code:%d\n",WSAGetLastError());
closesocket(sockclient);
WSACleanup();
return -1;
}
printf("%s\n",t);
}
return 0;
}
int getline(char* s,int max)
{
int i = 0;
char c;
while (--max >0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if (c = '\n')
s[i] = '\0';
return i;
}