Implementing chat room programs 1.vc network programming and Windows Sockets API profile with VC 6.0 Sockets API
VC supports network programming with socket support, Wininet support, MAPI, and ISAPI support. Among them, the Windows Sockets API is a TCP / IP network environment and is also the most common API on the Internet. The earliest American University Berkeley has developed an API for TCP / IP protocol under UNIX. This API is a famous Berkeley Socket interface (socket). After the desktop operating system enters the Windows era, the socket method is still inherited. In TCP / IP network communication environments, Socket data transfer is a special I / O, which is equivalent to a file descriptor with a function called-Socket () similar to the open file. It can be understood that Socket is actually a communication endpoint, through which the user's Socket program can communicate over the network and other socket applications. Socket exists in a "communication domain" (an abstract concept introduced to describe how a general thread is communicated with Socket, and exchange data with another domain. Socket has three categories. The first is SOCK_STREAM (streaming) to provide a connection-oriented reliable communication service, such as Telnet, HTTP. The second is SOCK_DGRAM (datagram), providing communication with unconnectless communication, such as UDP. The third is SOCK_RAW (original), mainly used for the development and test of protocols, support communication underlying operations, such as direct access to IP and ICMP.
2.Windows Socket mechanism analysis
2.1 Some basic Socket systems call
The main system calls include: socket () - Create Socket; Bind () - Binds the created Socket and the local port; Connect () and acception () - create a socket connection; Listen () - server monitoring request; Send () - the controlled buffer transmission of the data; RECV () - controllable buffer reception; CloseSocket () - Turn off the socket.
2.2Windows socket starts and termination
Start function WSAStartup () establishes a connection to the Windows Sockets DLL, and the termination function wsaclearup () terminates the use of the DLL, which must be used.
2.3 Asynchronous selection mechanism
Windows is a non-seizuated operating system without taking UNIX blocking mechanism. When a communication event is generated, the operating system should process the event based on the settings, and the WSAAsYNCselect () function is the corresponding event to select the system. When Socket receives one of the setup network events, a message will be given to the program window. This message will specify the Socket that generates a network event, an event type and error code that occurs.
2.4 Asynchronous data transmission mechanism
WSaasyncselect () Sets a WM_Socket message to the window after the response communication event is required to respond to the communication event on the Socket. In the callback function of the window, the corresponding data transfer processing code should be added.
3. Description of the chat room program
3.1 Implementing ideas
The chat room program on the Internet is generally served with a server-side connection response. The user can log in to the server through the client program to the user on the same server, which is a connection-oriented communication process. Therefore, the program is to implement two part of the server and the client in the TCP / IP environment.
3.2 Server workflow
The server side creates a socket array with a socket () system (ie, the maximum number of receiving connection customers) is set, and Bind Bind () can be listened to the port to listen (). If there is a client connection request, select an empty socket in an array, assign the client address to this socket. Then log in successfully can chat on the server. 3.3 Client workflow
The client program is relatively simple, just establish a socket to connect and receive data by this socket after successfulness.
4. Core code analysis
Limited to the space, only the core code related to network programming is given, and other servers, such as chat text, display readers can be added by themselves.
4.1 Server-end code
Turn on the server function:
void OnServerOpen () // turn on the server function {WSADATA wsaData; int iErrorCode; char chInfo [64]; if (WSAStartup (WINSOCK_VERSION, & wsaData)) // calls the Windows Sockets DLL {MessageBeep (MB_ICONSTOP); MessageBox ( "Winsock could not be initialized! ", AFXGetAppname (), MB_OK | MB_ICONSTOP); wsacleanup (); return;} else wsacleanup (); if (gethostname (chinfo, sizeof (chinfo))) {ReportWinsockerR (" / n unable to get hosts! / N "); Return;} cstring cswinsockid = "/ n == >> The server function is on port: no."; cswinsockid = itoa (m_pdoc-> m_nserverport, chinfo, 10); cswinsockid = "/ n"; PrintString (CSWinsockID) / / In the program view display the function of the prompt information, the reader can create m_pdoc-> m_hserversocket = socket (pf_inet, sock_stream, default_protocol); // Create server-side socket, type SOCK_STREAM, connected communication if (m_pdoc-> m_hServerSocket == INVALID_SOCKET) {ReportWinsockErr ( "Unable to create server socket!"); return;} m_pDoc-> m_sockServerAddr.sin_family = AF_INET; m_pDoc-> m_sockServerAddr.sin_addr.s_addr = INADDR_ANY; m_pDoc-> m_sockServerAddr.sin_port = htons (m_pDoc -> m_nserverport; if (bind (m_pdoc-> m_hserversocket, (lpsockAddr) & m_pdo c-> m_sockServerAddr, sizeof (m_pDoc-> m_sockServerAddr)) == SOCKET_ERROR) // with the selected port binding {ReportWinsockErr ( "Unable to bind server socket!"); return;} iErrorCode = WSAAsyncSelect (m_pDoc-> m_hServerSocket , m_hwnd, wm_server_accept, fd_accept); // Set the server corresponding network event to fd_accept, the connection request, // generate the corresponding pass to the window for WM_SERVER_ACCEPT IF (IerrorCode == Socket_ERROR) {ReportWinsocker ("WsaasyncSelect setting failed ! "); Return;}} (listen (m_pdoc-> m_hserversocket, queue_size) == Socket_ERROR) // Start listening to customer connection request {ReportWinsockerr (" Server Socket Monitor Failed! ");
m_pparentMenu-> EnableMenuitem (id_server_open, mf_enable); Return;} m_bserverisopen = true; // Monitor if the server is turned on;} Responding to customers send chat text to the server: on_mentage (wm_client_read, onclientRead)
Lresult OnClientRead (WParam WPARAM, LPARAM LPARAM) {INT IREAD; INT IeNfferLength; INT IEND; INT IREMAINSPACE; CHAR chinbuffler [1024]; int i; for (i = 0; (i = 0; "I // maxClient is the maximum number of servers responsive connection {} if (i == mAXClient) return 0L; iBufferLength = iRemainSpace = sizeof (chInBuffer); iEnd = 0; iRemainSpace - = iEnd; iBytesRead = recv (m_aClientSocket [i], (LPSTR) (chInBuffer iEnd), iSpaceRemaining, NO_FLAGS); // with a controllable buffer reception function RECV () to receive character IEND = IREAD; if (ibytesread == Socket_ERROR) ReportWinsockerR ("Recv error!"); Chinbuffer [iend] = '/ 0'; if (lstrlen (chinbuffer)! = 0) {PrintString (chinbuffer); // server-side text Displays ONSERVERBROADCAST (chinbuffer); // ourselves the function to broadcast this customer to all connected customers} return (0L);}
For the customer disconnection, an FD_CLOSE message will be generated, which is only necessary to close the corresponding socket with closesocket (), which is relatively simple.
4.2 client code
Connect to the server:
void OnSocketConnect () {WSADATA wsaData; DWORD dwIPAddr; SOCKADDR_IN sockAddr; if (WSAStartup (WINSOCK_VERSION, & wsaData)) // calls the Windows Sockets DLL {MessageBox (, NULL, MB_OK "Winsock could not be initialized!"); return;} m_hSocket = socket (PF_INET, SOCK_STREAM, 0); // Create a connected socket SockAddr.sin_Family = AF_INET; // Using TCP / IP Protocol SockAddr.SIN_PORT = m_Iport; // The client specified IP address SOCKADDR.SIN_ADDR.S_UN.S_ADDR = Dwipaddr; int nConnect = Connect (M_HSocket, (LPSOCKADDR) & SockAddr, SIZEOF (SockAddr)); // Request to connect If (NConnect) ReportWinsockerr ("Connection Failure!"); Else MessageBox ("Connection Success!", NULL, MB_OK) INT iERRORCODE = WSAASYNCSELECT (M_HSocket, M_HWND, WM_SOCKET_READ, FD_READ); / / Specify the response event, send the server to the server to character if (IrrorCode == Socket_ERROR) MessageBox ("WsaasyncseLect Failure!");} Receive Server The characters also use the controllable buffer reception function RECV (), the client chat character Send the data controller buffer send function Send (), which is relatively simple, and it will not be described here.
5. Small knot
By booking through the writing room program, you can basically understand the basic procedures and essentials of the Windows Sockets API programming. This program compiled in VC 6.0, runs well in a local area using Windows 98 / NT.