//服务端程序 #define _CRT_SECURE_NO_WARNINGS #include "winsock2.h" #include "stdio.h" #include "time.h" #pragma comment(lib,"WS2_32.lib") #define MAX_BUFFER 1024 /*服务器缓冲区的最大值为1024个字符*/ //#define NULL 0 #define DAYTIME_SERVER_PORT 13 /*常量表示服务器的端口号为13*/ int main() { SOCKET serverFd; int connectionFd, i = 1; /*统计客户请求次数*/ struct sockaddr_in servaddr; char timebuffer[MAX_BUFFER + 1]; time_t currentTime; WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { printf("命令套接口初始化失败 "); WSACleanup();//终止使用Winsock DLL库,释放系统资源 return-1; } serverFd = socket(AF_INET, SOCK_STREAM, 0); /*创建服务器端的套接字,三个参数分别代表 使用TCP/IP;传输过程使用TCP;不适用其他特殊协议*/ if (serverFd == -1) { printf("socket error! "); WSACleanup();//终止使用Winsock DLL库,释放系统资源 return(-1); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); /*将4字节主机字节数顺序转换到网络字节顺序*/ servaddr.sin_port = htons(DAYTIME_SERVER_PORT);/*将4字节主机字节数顺序转换到网络字节顺序*/ if (bind(serverFd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == SOCKET_ERROR)/*地址绑定*/ { printf("bind( ) Failed: %d ", WSAGetLastError()); WSACleanup();//终止使用Winsock DLL库,释放系统资源 return(-1); } listen(serverFd, 5);/*监听客户端的连接请求,定义最大的链接次数为5次*/ printf("daytime服务器已经启动,正在监听来自客户端的服务请求...... ");//运行界面上提示服务器软件处于启动状态 while (1) { connectionFd = accept(serverFd, (struct sockaddr *)NULL, NULL);/*连接建立后将存放在缓冲区的时间发送到客户端*/ if (connectionFd >= 0) { currentTime = time(NULL); sprintf(timebuffer, "%s ", ctime(¤tTime)); printf("已有%d个访问者 ", i++); send(connectionFd, timebuffer, strlen(timebuffer), 0); closesocket(connectionFd); } } WSACleanup();//终止使用Winsock DLL库,释放系统资源 return(1); }
//客户端程序 #include "winsock2.h" #include "stdio.h" #include "time.h" #pragma comment(lib,"WS2_32.lib") #define MAX_BUFFER 1024 /*客户机缓冲区的最大值为1024个字符*/ #define DAYTIME_SERVER_PORT 13 /*常量表示服务器的端口号为13*/ int main() { SOCKET connectionFd; int in; struct sockaddr_in servaddr; char timebuffer[MAX_BUFFER + 1]; time_t currentTime; WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { printf("命令套接口初始化失败 "); return-1; } connectionFd = socket(AF_INET, SOCK_STREAM, 0); /*创建服务器端的套接字,三个参数分别代表 使用TCP/IP;传输过程使用TCP;不适用其他特殊协议*/ if (connectionFd == -1) { printf("socket error! "); return(-1); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(DAYTIME_SERVER_PORT);/*将4字节主机字节数顺序转换到网络字节顺序*/ //inet_addr()函数把字符串形式的IP地址转换为unsiged long型的整数值 servaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); /*此处设置daytime服务器所在机器IP地址,应根据实际情况确定*/ if (connect(connectionFd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == INVALID_SOCKET) { printf("connect() failed:%d ", WSAGetLastError());//在界面上输出连接失败的错误提示信息 return(0); } while ((in = recv(connectionFd, timebuffer, MAX_BUFFER, 0))>0) { timebuffer[in] = 0; printf(" %s", timebuffer); } closesocket(connectionFd); WSACleanup();//终止使用Winsock DLL库,释放系统资源 return(1); }