//A SOCKET is simply a typedef for an unsigned int. //In Unix, socket handles were just about same as file //handles which were again unsigned ints. //Since this cannot be entirely true under Windows //a new data type called SOCKET was defined.
//定义一个socket句柄作为服务器 SOCKET server;
//WSADATA is a struct that is filled up by the call //to WSAStartup
//这是一个结构体,用于调用函数WSAStartup时作为参数 WSADATA wsaData;
//The sockaddr_in specifies the address of the socket //for TCP/IP sockets. Other protocols use similar structures.
//存放ip地址的结构体 sockaddr_in local;
//WSAStartup initializes the program for calling WinSock. //The first parameter specifies the highest version of the //WinSock specification, the program is allowed to use.
//初始化winsock,每次必须最先调用 int wsaret=WSAStartup(0x101,&wsaData);
//WSAStartup returns zero on success. //If it fails we exit.
//测试初始化是否成功 if(wsaret!=0) { return 0; }
//Now we populate the sockaddr_in structure
//填充服务器的ip地址和端口号 local.sin_family=AF_INET; //Address family local.sin_addr.s_addr=INADDR_ANY; //Wild card IP address local.sin_port=htons((u_short)8888); //port to use
//If the socket() function fails we exit if(server==INVALID_SOCKET) { return 0; }
//bind links the socket we just created with the sockaddr_in //structure. Basically it connects the socket with //the local address and a specified port. //If it returns non-zero quit, as this indicates error
//close the client socket //关闭连接 closesocket(client);
}
//closesocket() closes the socket and releases the socket descriptor //释放socket资源 closesocket(server);
//originally this function probably had some use //currently this is just for backward compatibility //but it is safer to call it as I still believe some //implementations use this to terminate use of WS2_32.DLL //必须作的最后的事 WSACleanup();
return 0; }
(五)运行: 服务器端:
E:/work/Server/Debug>server Press ESCAPE to terminate program Starting up TCP server Connection from 203.200.100.122 Connection from 127.0.0.1 E:/work/Server/Debug>
客户端:
E:/work/Server/Debug>telnet 202.89.211.88 8888 Trying 202.89.211.88... Connected to 202.89.211.88. Escape character is '^]'. Your IP is 203.200.100.122 Connection closed by foreign host.