The following is a simple blocking mode server. It is a single-to-single server. If you want to implement a multi-client server, you need to use other I/O models!
# Include <cstdlib>
# Include <iostream>
# Include <winsock2.h>
# Pragma comment (Lib, "libws2_32.lib ")
// Buffer size
# Define data_bufsize 4096
Using namespace STD;
Const unsigned int nport = 5151;
Int main (INT argc, char * argv [])
{
Wsadata;
Socket listen;
Socket accept;
Char buffer [data_bufsize];
// Initialize Winsock 2.2
Int ret = wsastartup (makeword (2, 2), & wsadata );
If (Ret! = 0)
{
// Note: Because Winsock is not loaded, we cannot use wsagetlasterror
// To identify the specific error that causes the fault. We can only judge based on the returned status
Cout <"wsastartup failed with error" <RET <Endl;
Wsacleanup ();
Return 0;
}
// Here we create a socket to connect or listen to the code.
Listen = socket (af_inet, sock_stream, ipproto_tcp );
// Set the sockaddr_in of the server
Sockaddr_in serverddr;
Serverddr. sin_family = af_inet;
Serverddr. sin_addr.s_un.s_addr = htonl (inaddr_any );
Serverddr. sin_port = htons (nport );
// Bind the listening socket
Int nret = BIND (Listen, (lpsockaddr) & serverddr, sizeof (serverddr ));
If (nret = socket_error)
{
Cout <"BIND error! "<Endl;
Closesocket (Listen );
Goto error1;
}
// Accept. The last parameter can be null. For example:
// Accept = accept (Listen, null, null );
// If you want to obtain the client's IP address
Sockaddr_in acceptaddr;
Int acceptaddrlen;
Accept = accept (Listen, (lpsockaddr) & acceptaddr, & acceptaddrlen );
// Print the Client IP address and port number
Cout <"IP Address:" <inet_ntoa (acceptaddr. sin_addr) <Endl;
Cout <"port is:" <ntohs (acceptaddr. sin_port) <Endl;
Nret = 0;
While (1)
{
// Receive data
Nret = Recv (accept, buffer, data_bufsize, 0 );
If (nret = socket_error)
{
Cout <"Recv error! "<Endl;
Closesocket (accept );
Closesocket (Listen );
Goto error1;
}
}
Closesocket (accept );
Closesocket (Listen );
Error1:
// If the program ends, wsacleanup is called.
Wsacleanup ();
System ("pause ");
Return exit_success;
}