首次使用“winsock.in”可能导致部分函数不可用,解决方法参考博客
/*TCPdaytime*/
#include<cstdlib>
#include<cstdio>
#include<winsock.h>
#include<string>
using namespace std;
void TCPdaytime(const char*,const char*);
void errexit(const char*,...);
SOCKET connectTCP(const char*, const char*);
#define LINELEN 128
#define WSVERS MAKEWORD(2,0)
/*
main - TCP client for DAYTIME serive
*/
int main(int argc, char* argv[])
{
string host = "localhost"; //客户端和服务器端位于同一主机
string service = "daytime"; //标准服务名
WSADATA wsadata;
switch (argc)
{
case 1:
host = "localhost";
break;
case 3:
service = argv[2];
/* FALL THROUGH */
case 2:
host = argv[1];
break;
default:
fprintf(stderr, "usage:TCPdaytime [host [port]]\n");
exit(1);
}
if (WSAStartup(WSVERS, &wsadata) != 0) //Win环境下建立套接字必须先调用
//errexit("WSAStartup failed\n");
TCPdaytime(host.c_str(), service.c_str()); //完成时间请求服务
WSACleanup();
return 0;
}
/*
TCPdaytime - invoke Daytime on specified host and print results
*/
void TCPdaytime(const char* host, const char* service)
{
char buf[LINELEN + 1]; //buffer for one line of text
SOCKET s; //socket descriptor
int cc; //recv character count
s = connectTCP(host, service); //创建TCP套接字并于服务器连接
cc = recv(s, buf, LINELEN, 0); //完成数据接受
while (cc != SOCKET_ERROR and cc > 0)
{
buf[cc] = '\0';
(void)fputs(buf, stdout);
cc = recv(s, buf, LINELEN, 0);
}
closesocket(s);
}
参考MOOC上哈尔滨工业大学的计算机网络公开课