Sever端:
#include"WinSock2.h"
#include "time.h"
#include "stdio.h"
#include <iostream>
#pragma comment(lib,"WS2_32")
using namespace std;
const int MaxLine = 1024;
int main()
{
int lRet = 0;
WSADATA lWsaData;
if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0)
{
cout << "Error " << lRet << endl;
return 0;
}
int lListen = 0, lConnfd = 0;
SOCKADDR_IN lServAddr;
char lBuf[MaxLine];
time_t lTicks;
lServAddr.sin_family = AF_INET;
lServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
lServAddr.sin_port = htons(13);
SOCKET lSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == lSocket)
{
cout << "INVALID_SOCKET" << endl;
return 0;
}
bind(lSocket,(sockaddr*)(&lServAddr),sizeof(lServAddr));
listen(lSocket,5);
while(true)
{
SOCKET lSeverSocket = accept(lSocket,(sockaddr*)NULL,NULL);
lTicks = time(NULL);
sprintf(lBuf, "%.24s\r\n", ctime(&lTicks));
send(lSeverSocket,lBuf,strlen(lBuf),0);
closesocket(lSeverSocket);
}
}
Client 端:
#include<WinSock2.h>
#include <iostream>
#include <string>
using namespace std;
#pragma comment(lib, "WS2_32")
const int MaxLine = 1024;
int main()
{
char lReadline[MaxLine];
int lRet = 0;
WSADATA lWsaData;
if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0)
{
cout << "Error " << lRet << endl;
return 0;
}
SOCKADDR_IN lAddr;
lAddr.sin_family = AF_INET;
lAddr.sin_port = htons(13);
SOCKET lSocket = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == lSocket)
{
cout << "INVALID_SOCKET" << endl;
return 0;
}
lAddr.sin_addr.s_addr = inet_addr("192.168.1.102");
if (connect(lSocket,(sockaddr*)(&lAddr),sizeof(lAddr)) < 0 )
{
cout << "connect error" << endl;
return 0;
}
int lNum = 0;
if ( (lNum = recv(lSocket,lReadline,MaxLine,0)) > 0)
{
string lStr(lReadline,lNum-1);
cout << lStr << endl;
}
return 0;
}
具体含义可以参考原书,Stevens大师已经事无巨细地把每行代码都做了解释,感觉很适合初学者学习。
对于网络编程,我是初学者,在这里想把书中的原理搞明白,把代码自己敲成winsock下的,至少把代码重新看一遍吧,呵呵。
勿在浮沙筑高台!——侯捷。
牢记侯捷大师的名言!