网学网为广大网友收集整理了,WinSock初学入门:实现TCP服务器,希望对大家有所帮助!
(一)介绍:
本文主要采用Winsock API实现了一个Tcp服务器。对初学者而言,相当实用。
(二)准备工作:
1、使用vc6向导建立控制台工程(console application),并选择支持MFC。
2、在stdafx.h中加入头文件conio.h和winsock2.h。
3、在头文件中加入:#pragma comment(lib, "ws2_32.lib")。
(三)主程序:主要是启动服务器线程并等待用户退出的命令。
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
cout << "Press ESCAPE to terminate program\r\n";
AfxBeginThread(ServerThread,0); //启动一条线程
while(_getch()!=27); //用户按ESC键则退出
return nRetCode;
}
(四)线程代码:一个简单的tcp服务器,返回客户的ip地址。
UINT ServerThread(LPVOID pParam)
{
cout << "Starting up TCP server\r\n";
//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
//the socket function creates our SOCKET
//建立一个tcp socket
server=socket(AF_INET,SOCK_STREAM,0);
//If the socket() function fails we exit
if(server==INVALI
[1] [2] [3] 下一页