Unix網絡編程chapter1 示例程序改寫為Winsock:
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下的,至少把代碼重新看一遍吧,呵呵。