server.cpp
资源名称:1731.rar [点击查看]
上传用户:swkcbjrc
上传日期:2016-04-02
资源大小:45277k
文件大小:3k
源码类别:
游戏
开发平台:
Visual C++
- //===========================================================
- //示例程序:演示如何通过Winsock编程实现简单的时间/日期服务程序
- //编写:suyu 2003/06 完整程序示例在随书配套光盘
- //============================================================
- #include "stdafx.h"
- #include "winsock.h"
- #include "stdlib.h"
- #include "stdio.h"
- void usage(char *name)
- {
- fprintf(stderr, "usage: %s [port]n", name);
- }
- int main(int argc,char *argv[])
- {
- SOCKET servsock,clisock;
- struct sockaddr_in sa;
- struct sockaddr_in cliaddr; /* 存放返回的客户地址信息 */
- int len;
- int err;
- int servport = 5555; /* 默认服务端口 */
- char buff[256]; /* 存放时间/日期信息的缓冲区 */
- SYSTEMTIME st;
- WSADATA wsd;
- printf("************************************************************n");
- printf("*time server sample,written by suyu,chenyun");
- printf("*mail:wantsoft@163.com n");
- printf("************************************************************n");
- /* 处理命令行参数 */
- if (argc > 2)
- {
- usage(argv[0]);
- return -1;
- }
- if (argc == 2)
- {
- servport = atoi(argv[1]);
- if (servport > 65535 || servport < 1)
- {
- usage(argv[0]);
- return -2;
- }
- }
- /* 初始化Winsock1.1 */
- if (WSAStartup(MAKEWORD(1,1), &wsd) != 0)
- {
- printf("WSAStartup() failed !n");
- return -3;
- }
- /* 创建套接字 */
- printf("create socket ...n");
- servsock = socket(AF_INET, SOCK_STREAM, 0);
- if (servsock == INVALID_SOCKET)
- {
- fprintf(stderr, "socket() failed: %dn", WSAGetLastError());
- return -4;
- }
- printf("[OK]n");
- /* 填充服务器地址结构 */
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- sa.sin_port = htons(servport);
- sa.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- /* 绑定套接字到服务器地址结构 */
- printf("bind ...n");
- err = bind(servsock, (const sockaddr *)&sa,sizeof(sa));
- if (err != 0)
- {
- fprintf(stderr, "bind() failed: %dn", WSAGetLastError());
- return -5;
- }
- printf("[OK]n");
- /* 监听套接字 */
- printf("listen ...n");
- err = listen(servsock,5);
- if (err != 0)
- {
- fprintf(stderr, "listen() failed: %dn", WSAGetLastError());
- return -6;
- }
- printf("[OK]n");
- /* 循环接受连接请求 */
- while(1)
- {
- printf("wait request ...n");
- len = sizeof(cliaddr);
- clisock = accept(servsock, (struct sockaddr *)&cliaddr, &len);
- if (clisock == INVALID_SOCKET)
- {
- fprintf(stderr, "accept() failed: %dn", WSAGetLastError());
- closesocket(servsock);
- return -7;
- }
- printf("accept client: %s:%dn", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
- GetLocalTime(&st); /* 得到本地时间/日期 */
- /* 为返回给客户整理时间/日期信息格式 */
- sprintf(buff,"YEAR : %u nMONTH : %u nDAY : %u nHOUR: %u nMINUTE : %u nSECOND : %u n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
- send(clisock, buff, strlen(buff), 0); /* 发送给客户 */
- closesocket(clisock); /* 关闭与客户的连接 */
- printf("[server OK]n");
- }
- closesocket(servsock); /* 关闭服务套接字 */
- WSACleanup(); /* 释放资源 */
- return 0;
- }