posts - 29,comments - 10,trackbacks - 0

今天学习了些关于VC网络编程中关于Winsock的知识,并做了相应的整理。在这里根据了一个聊天室例子帮助我了解这些知识的用法。
(1)Server端调用函数顺序:
         WSAStartup()初始化Winsock
         socket()创建一个监听Socket
         bind()为监听Socket指定通信对象
         listen()设置等待连接状态
         accept()接收连接并生成会话Socket
         send和recv进行对话
         closesocket()关闭socket
(2)Client端调用函数顺序
         WSAStartup()初始化Winsock
         socket()创建一个监听Socket
         connect()与Server端连接
         send和recv进行对话
         closesocket()关闭socket
1、程序头部分,包括引用的头文件、宏定义、全局变量和函数声明

#include "stdafx.h"
#include 
"resource.h"
#include 
<VECTOR>                        //采用STL
#include <algorithm>
#include 
<WINSOCK2.H>                    //调用winsock                        
#include <ASSERT.H>

#define BUFFER_SIZE 4096               //缓冲区的大小
#define SERVER_MESSAGE WM_USER+100        //服务器SOCKET异步消息ID
#define CLIENT_MESSAGE WM_USER+101      //客户机SOCKET异步消息ID

// Global Variables:
SOCKET g_ListenSocket;                //Listen socket (for server)
std::vector<SOCKET>  g_DataSockets;    //All data sockets with clients (for server)
SOCKET g_ClientSocket;                //Client data socket (for client)
BOOL g_bActive;                        //A tag of active socket (for both server and client)
std::string g_ChatWords;
BOOL g_bClient;                        
//TRUE as a client, FALSE as a server

BOOL ServerInit(HWND hWnd,UINT port);
BOOL ClientInit(HWND hWnd,UINT port,
const char* serverIP);
int OnClientMessage(HWND hWnd, WPARAM wParam, LPARAM lParam);
int OnServerMessage(HWND hWnd, WPARAM wParam, LPARAM lParam);
void SendMessageToPeer(HWND hWnd);
void Send(SOCKET sock, const char* buffer, int length);
void RefreshScreen(HWND hWnd);
void ExitChat(HWND hWnd);
void GetErrorReason();
2、Win32程序函数入口点WinMain:
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     
int       nCmdShow)
{
    
// Perform application initialization:
    g_bActive=FALSE;
    DialogBox(hInstance, MAKEINTRESOURCE(IDD_CHAT_DIALOG), NULL, (DLGPROC)WndProc);
    
return 0;
}
3、对话框的消息循环函数WndProc:
      WndProc消息循环中,只处理4中消息:对话框初始化、对话框控件、服务器SOCKET异步和客户端SOCKET异步,在对话框初始化中,程序启动了SOCKET栈。在对话框控件中,程序分别响应了各种按钮消息以及文字输入框消息EN_UPDATE。在服务器SOCKET异步消息中,调用OnServerMessage处理。在客户端SOCKET异步消息中,调用了OnclientMessage处理。
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    HWND subWnd;
    
char buffer[BUFFER_SIZE];
    UINT port;
    
char serverIP[16];
    
switch (message)
    
{
    
case WM_INITDIALOG:
        
{
            WSADATA wsaData;
            
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
            
{
                MessageBox(hWnd,
"Socket Stack Error!","Error",IDOK);
                
return -1;
            }

        }

        
return TRUE;
    
case WM_COMMAND:
        
{
            
switch(LOWORD(wParam))
            
{
            
case IDOK:
            
case IDCANCEL:
                EndDialog(hWnd,LOWORD(wParam));
                
break;
            
case IDC_CONNECT:
                
{
                    subWnd
=GetDlgItem(hWnd,IDC_LISTEN_PORT_C);
                    GetWindowText(subWnd,buffer, BUFFER_SIZE);
                    port
= UINT(atoi(buffer));
                    subWnd
=GetDlgItem(hWnd,IDC_SERVERIP);
                    GetWindowText(subWnd,buffer,BUFFER_SIZE);
                    strncpy(serverIP,buffer,
16);
                    ClientInit(hWnd,port,serverIP);
                    
//g_ChatWords="";
                }

                
break;
            
case IDC_LISTEN:
                
{
                    subWnd
=GetDlgItem(hWnd,IDC_LISTEN_PORT_S);
                    GetWindowText(subWnd,buffer, BUFFER_SIZE);
                    port
= UINT(atoi(buffer));
                    ServerInit(hWnd,port);
                    
//g_ChatWords="";
                }

                
break;
            
case IDC_INPUTTEXT:
                
{
                    
if(HIWORD(wParam)==EN_UPDATE)
                    
{
                        SendMessageToPeer(hWnd);
                    }

                }

            
default:
                
break;
            }

        }

        
break;
    
case SERVER_MESSAGE:
        
{
            OnServerMessage(hWnd,wParam, lParam);
        }

        
break;
    
case CLIENT_MESSAGE:
        
{
            OnClientMessage(hWnd, wParam, lParam);
        }

        
break;
    }

    
return 0;
}

1)int WSAStartup(WORD wVersionRequested,LPWSADATA lpWSAData);
      
wVersionRequested:表示欲使用的Windows Sockets API版本,使用宏MAKEWORDXY)设置参数。表示版本为X.Y(本例中为2.2)
4、客户端初始化函数ClientInit:

   当单击“连接服务器“按钮时,程序分别从子窗口IDC_LISTEN_POST_CIDC_SERVERIP中提取服务器的IP和监听端口,然后调用客户端函数ClientInit

BOOL ClientInit(HWND hWnd,UINT port,const char* serverIP)
{
    sockaddr_in addr;
    ExitChat(hWnd);
    g_bClient
=TRUE;
    
if(inet_addr(serverIP)==INADDR_NONE)
    
{
        MessageBox(hWnd,
"Invalid IP Address!","Warnning",IDOK);
        
return FALSE;
    }


    
//create tcp/stream data socket
    g_ClientSocket = socket(AF_INET, SOCK_STREAM,0);
    assert(g_ClientSocket 
!= INVALID_SOCKET);

    
//set the socket as async selection tag, the related message is CLIENT_MESSAGE
    
//the async events contain: read, write, close, connect
    WSAAsyncSelect(g_ClientSocket,hWnd,CLIENT_MESSAGE,FD_READ|FD_WRITE|FD_CLOSE|FD_CONNECT);

    
//set the server address and port
    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr 
= inet_addr(serverIP);
    addr.sin_port 
= htons(port);   //short from host to network format
    
    
//connect to server
    connect(g_ClientSocket, (sockaddr*)&addr, sizeof(addr));

    g_ChatWords
+="Connecting\r\n";
    RefreshScreen(hWnd);
    
return TRUE;
}

1SOCKET socket(int af,int type,int protocol);

       af:指协议的地址族,如果想建立一个UDPTCP的套接字,则该值设置成AF_INET,表示在网络层采用网际协议(IP

       type:协议的套接字类型,可以是SOCK_STREAMSOCK_DGRAM SOCK_RAWSOCK_RDMSOCK_SEQPACKET 当采用流连接方式时用SOCK_STREAM,采用数据报文方式用SOCK_DGRAM

       proctocol:协议字段,当aftype都指定之后,该值的取值范围就被去定了,默认值为0

2int PASCAL FAR WSAAsyncSelect ( SOCKET s, HWND hWnd, unsigned int wMsg, long lEvent );

S:标识一个需要事件通知的套接口的描述符.

hWnd:标识一个在网络事件发生时需要接收消息的窗口句柄.

wMsg :在网络事件发生时要接收的消息.

lEvent:位屏蔽码,用于指明应用程序感兴趣的网络事件集合.

3int connect(SOCKET s,const struct sockaddr FAR * name,int namelen);

       S是建立好的套接字,name指向描述通信对象地址信息的结构体的指针,namelen是该结构体的长度。

4struct sockaddr_in {short sin_family;u_short sin_port;struct in_addr sin_addr;char    sin_zero[8];};

5unsigned long PASCAL FAR inet_addr( const struct FAR* cp);

  cp:一个以Internet标准“.”间隔的字符串。

本函数解释cp参数中的字符串,这个字符串用Internet“.”间隔格式表示一个数字的Internet地址。

6u_short PASCAL FAR htons( u_short hostshort);

  hostshort:主机字节顺序表达的16位数。

  本函数将一个16位数从主机字节顺序转换成网络字节顺序。

       其中sin_family是指地址族;sin_port是制定的端口号;sin_addr是制定的IP地址;sin_zero冗余字段,使sockaddr_in结构和SOCKADDR结构大小相同
5、服务器初始化函数ServerInit:
   单击“建立服务器“按钮时,程序从子窗口IDC_LISTEN_PORT_S中提取监听端口,然后调用服务器初始化函数ServerInit

BOOL ServerInit(HWND hWnd,UINT port)
{
    sockaddr_in addr;
    
char buffer[BUFFER_SIZE];
    ExitChat(hWnd);
    g_bClient
=FALSE;
    
    
//create a tcp/stream based socket
    g_ListenSocket = socket(AF_INET, SOCK_STREAM,0);
    assert(g_ListenSocket 
!= INVALID_SOCKET);

    
//set the socket as async selection tag, the related message is SERVER_MESSAGE
    
//the async events contain: accept, read, write, close
    WSAAsyncSelect(g_ListenSocket, hWnd, SERVER_MESSAGE, FD_ACCEPT|FD_READ|FD_WRITE|FD_CLOSE);

    addr.sin_family 
= AF_INET;  //IP layer takes IP router protocol
    addr.sin_addr.S_un.S_addr = INADDR_ANY;    
    addr.sin_port 
= htons(port);//port from short of host to short of network

    
//binding listening socket
    if(bind(g_ListenSocket, (sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)
    
{
        sprintf(buffer,
"Port %d has been taken. Change another port.\r\n",port);
        g_ChatWords
+=buffer;
        RefreshScreen(hWnd);
        MessageBox(hWnd,
"Binding Error","Warnning",IDOK);
        
return FALSE;
    }

    
    
//listening
    if(listen(g_ListenSocket, 5== SOCKET_ERROR)
    
{
        strcpy(buffer,
"Listen error.\r\n");
        g_ChatWords
+=buffer;
        RefreshScreen(hWnd);
        MessageBox(hWnd,
"Listen Error.","Warnning",IDOK);
        
return FALSE;
    }


    g_ChatWords
+="Server is listening\r\n";
    RefreshScreen(hWnd);
    g_bActive
=TRUE;
    
return TRUE;
}

1)  int bind(SOCKET s,const struct sockaddr FAR * name,int namelen);

S是建立好的套接字,name指向描述通信对象地址信息的结构体的指针,namelen是该结构体的长度。

2)int listen(SOCKET s,int backlog);

S是建立好的套接字,backlog是并发连接等待队列的长度。

6、SendMessageToPeer函数:
   当用户在文本框中输入文字时,程序会接收到该文本框的
EN_UPDATE消息,函数SendMessageToPeer负责处理该消息。在SendMessageToPeer中,一旦检测到用户按下了回车键,程序就将文本内容刷新到上面的显示框中,如果当前在线,文本内容还将发送到会话的另一端。

void SendMessageToPeer(HWND hWnd)
{
    HWND subwnd;
    
char buffer[BUFFER_SIZE];
    
int i;
    
static int oldNumOfChars=0;

    subwnd
=GetDlgItem(hWnd,IDC_INPUTTEXT);
    GetWindowText(subwnd,buffer,BUFFER_SIZE
-2);
    
if(oldNumOfChars!=strlen(buffer))
    
{
        oldNumOfChars
=strlen(buffer);
        
return;
    }

    
//CString s;
    
//s("%d还是%d",oldNumOfChars,strlen(buffer));
//    g_ChatWords+=s;
    
//empty content of input edit box
    SetWindowText(subwnd,"");
    oldNumOfChars
=0;
    
if(!g_bActive)
    
{
        g_ChatWords
+=buffer;
        g_ChatWords.erase(g_ChatWords.size(),
1);
        g_ChatWords
+="(Hint: you are isolated now.)\r\n";
        RefreshScreen(hWnd);
        
return;
    }

    strcat(buffer,
"\r\n");
    g_ChatWords
+=buffer;
    RefreshScreen(hWnd);
    
if(g_bClient)
    
{
        Send(g_ClientSocket, buffer, strlen(buffer));
    }

    
else
    
{
        
for(i=0;i<g_DataSockets.size();i++)
            Send(g_DataSockets[i],buffer,strlen(buffer));
    }

}

void Send(SOCKET sock, const char* buffer, int length)
{
    
int ret,i;
    i
=0;
    
while(length>0)
    
{
        ret
=send(sock,&(buffer[i]),length,0);
        
if(ret==0)
            
break;
        
else if(ret == SOCKET_ERROR)
        
{
            g_ChatWords
+="Error sending.\r\n";
            
break;
        }

        length
-=ret;
        i
+=ret;
    }

}

1)int send(SOCKET s,const char FAR * buf,int len,int flags);
参数s是建立连接的套接字。buflen是发送的数据包及其长度。flags一般取0,还有MSG_DONTROUTE要求套接字传输的数据不要路由,如果传输协议不支持该选项,则这个要求被忽略。MSG_OOB表示套接字此时传输的数据室外带数据,需要紧急处理。

7、OnClientMessage函数:

在主循环的消息循环中,OnClientMessage函数用来处理客户端SOCKET的一部消息CLIENT_MESSAGE。需要指出的是:当某个网络消息到达窗口时,可能暗含着套接字上发生了某种网络错误。此时,应该先判断套接字上是否发生了错误,如果有错误发生就直接关闭套接字然后返回,只有在没有错误发生的情况下,才需要处理具体的网络消息。在实现上,需要利用消息参数lParam的高字节,宏WSAGETSELECTERROR可以检测错误。而具体的消息类型是存储在lParam的低字节,宏WSAGETSELECTEVENT用来获取该低字节值。

int OnClientMessage(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    
char buffer[BUFFER_SIZE+1];
    
int retCode;
    sockaddr_in name;
    
int namelen=sizeof(sockaddr_in);

    
if(WSAGETSELECTERROR(lParam))
    
{
        closesocket(g_ClientSocket);
        strcpy(buffer,
"Server has no response.\r\n");
        g_ChatWords
+=buffer;
        RefreshScreen(hWnd);
        g_bActive
=FALSE;
        
return 0;
    }


    
switch(WSAGETSELECTEVENT(lParam))
    
{
        
case FD_CONNECT:
            getpeername(g_ClientSocket,(sockaddr
*)&name,&namelen);
            sprintf(buffer,
"Successfully connected to %s:%d.\r\n",inet_ntoa(name.sin_addr),ntohs(name.sin_port));
            g_ChatWords
+=buffer;
            RefreshScreen(hWnd);
            g_bActive
=TRUE;
            
break;
        
case FD_READ:
            retCode
=recv(g_ClientSocket,buffer,BUFFER_SIZE,0);
            
if(retCode!=SOCKET_ERROR)
            
{
                buffer[retCode]
=NULL;
                g_ChatWords
+=buffer;
            }

            
else
                GetErrorReason();
            RefreshScreen(hWnd);
            
break;
        
case FD_WRITE:
            
break;
        
case FD_CLOSE:
            closesocket(g_ClientSocket);
            strcpy(buffer,
"Server close session.Successfully log out.\r\n");
            g_ChatWords
+=buffer;
            RefreshScreen(hWnd);
            g_bActive
=FALSE;
            
break;
    }

    
return 0;
}

1char FAR* PASCAL FAR inet_ntoa( struct in_addr in);
      in:一个表示Internet主机地址的结构。
   
本函数将一个用in参数所表示的Internet地址结构转换成以“.” 间隔的诸如“a.b.c.d”的字符串形式。

2) int recv(SOCKET s,char FAR * buf,int len,int flags);
参数与send一致

3)int closesocket(SOCKET s);
关闭套接字

8、OnServerMessage函数:

在主程序的消息循环中,OnServerMessage函数用来处理客户端SOCKET的一部消息SERVER_MESSAGE。在服务器初始化函数中的g_ListenSocket被设置成异步监听socket,所有被g_ListenSocket接收的数据socket将同时被设置成异步socket,并共享同一个消息SERVER_MESSAGE。及时服务器关闭了监听socket,会话socket的连接依然有效,除非服务器同时也将会话socket关闭。

int OnServerMessage(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    SOCKET socket;
    
int i,retCode,namelen;
    
char buffer[BUFFER_SIZE+1];
    std::vector
<SOCKET>::iterator ite;
    sockaddr_in name;
    namelen
=sizeof(name);

    
if(WSAGETSELECTERROR(lParam))
    
{
        getpeername((SOCKET)wParam,(sockaddr
*)&name,&namelen);
        closesocket((SOCKET)wParam);
        
//erase the client socket from client socks list
        ite=std::find(g_DataSockets.begin(), g_DataSockets.end(),(SOCKET)wParam);
        assert(ite
!=g_DataSockets.end());
        g_DataSockets.erase(ite);
        
//refresh screen
        sprintf(buffer, "Client %s:%d lost contact with us.\r\n", inet_ntoa(name.sin_addr),ntohs(name.sin_port));
        
for(i=0; i<g_DataSockets.size(); i++)
            Send(g_DataSockets[i],buffer,strlen(buffer));
        g_ChatWords
+=buffer;
        RefreshScreen(hWnd);
        
return 0;
    }


    
switch(WSAGETSELECTEVENT(lParam))
    
{
        
case FD_ACCEPT:
            
//accept the client request
            socket= accept(g_ListenSocket,NULL,NULL);
            
//in fact we can get the peer when calling accept, here we use getpeername instead
            getpeername(socket,(sockaddr*)&name,&namelen);
            
//send a message of logining to other clients
            sprintf(buffer,"A guest joins us.(%s:%d)\r\n",inet_ntoa(name.sin_addr),ntohs(name.sin_port));
            g_ChatWords
+=buffer;
            
for(i=0;i<g_DataSockets.size();i++)
                Send(g_DataSockets[i],buffer,strlen(buffer));
            
//send a welcome message to current client
            sprintf(buffer, "Welcome !(You ID is: %s:%d.)\r\n",inet_ntoa(name.sin_addr),ntohs(name.sin_port));
            
//send(socket,buffer,strlen(buffer),0);
            Send(socket,buffer,strlen(buffer));
            
//refresh srceen text
            RefreshScreen(hWnd);
            
//push the client socket down to the client sockets list
            g_DataSockets.push_back(socket);
            
break;
        
case FD_READ:
            
{
                
//get the client message, the client socket ID is wParam
                retCode=recv((SOCKET)wParam,buffer,BUFFER_SIZE,0);
                buffer[retCode]
=NULL;
                
//send the received message to other clients
                for(i=0;i<g_DataSockets.size();i++)
                
{
                    
if(wParam!=g_DataSockets[i])
                        Send(g_DataSockets[i],buffer,strlen(buffer));
                }

                g_ChatWords
+=buffer;
                
//refresh screen
                RefreshScreen(hWnd);
            }

            
break;
        
case FD_WRITE:
            
return 0;
        
case FD_CLOSE: //Client gracefully close the socket
            
//close the client socket who has left, the client socket ID is wParam
            getpeername((SOCKET)wParam,(sockaddr*)&name,&namelen);
            closesocket((SOCKET)wParam);
            
//erase the client socket from client socks list
            ite=std::find(g_DataSockets.begin(), g_DataSockets.end(),(SOCKET)wParam);
            assert(ite
!=g_DataSockets.end());
            g_DataSockets.erase(ite);
            
//refresh screen
            sprintf(buffer, "Client %s:%d left.\r\n", inet_ntoa(name.sin_addr),ntohs(name.sin_port));
            
for(i=0; i<g_DataSockets.size(); i++)
                Send(g_DataSockets[i],buffer,strlen(buffer));
            g_ChatWords
+=buffer;
            RefreshScreen(hWnd);
            
break;
    }

    
return 0;
}

1int PASCAL FAR getpeername( SOCKET s, struct sockaddr FAR* name,int FAR* namelen);

  s:标识一已连接套接口的描述字。

  name:接收端地址的名字结构。

namelen:一个指向名字结构的指针。

2u_short PASCAL FAR ntohs( u_short netshort);

netshort:一个以网络字节顺序表达的16位数。

本函数将一个16位数由网络字节顺序转换为主机字节顺序。

3) SOCKET accept(SOCKET s,struct sockaddr FAR * addr,int FAR * addrlen);

如果是服务器并不关心对方的地址,则可将accept函数中后两个参数设置为NULL

9、最后,介绍3个辅助函数:ExitChat、GetErrorReason和RefreshScreen
      当新建服务器或链接服务器的时候,首先需要将上一次会话关闭,ExitChat函数完成此功能。
      RefreshScreen函数负责刷新显示内容并滚动显示文本框。
      GetErrorReason函数负责获得当前操作中的具体错误原因。
void ExitChat(HWND hWnd)
{
    
int i;
    
char buffer[BUFFER_SIZE];
    
if(g_bActive)
    
{
        
if(g_bClient)
        
{
            closesocket(g_ClientSocket);
            strcpy(buffer,
"Successfully log out.\r\n");
            g_ChatWords
+=buffer;
            RefreshScreen(hWnd);
        }

        
else
        
{
            strcpy(buffer,
"I will leave. Pls clients log out ASAP.\r\n");
            
for(i=0; i<g_DataSockets.size(); i++)
            
{
                Send(g_DataSockets[i],buffer,strlen(buffer));
                closesocket(g_DataSockets[i]);
            }

            g_DataSockets.clear();
            
            closesocket(g_ListenSocket);
            strcpy(buffer,
"Successfully close server.\r\n");
            g_ChatWords
+=buffer;
            RefreshScreen(hWnd);
        }

    }

    g_bActive
=FALSE;
}


void GetErrorReason()
{
    LPVOID lpMsgBuf;
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,WSAGetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) 
&lpMsgBuf,0,NULL);
    g_ChatWords
+=(char *)lpMsgBuf;
    LocalFree( lpMsgBuf );
}

void RefreshScreen(HWND hWnd)
{
    HWND subWnd;
    std::
string::size_type pos;
    
int n;
    subWnd
=GetDlgItem(hWnd,IDC_SHOWTEXT);
    SetWindowText(subWnd, g_ChatWords.c_str());
    n
=0;
    pos
=0;
    
while((pos=g_ChatWords.find('\n',pos))!=std::string::npos)
    
{
        pos
++;
        n
++;
    }

    SendMessage(subWnd, EM_LINESCROLL, 
0, n);
}

posted on 2009-06-21 00:23 The_Moment 阅读(1907) 评论(0)  编辑 收藏 引用 所属分类: VC理论

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理