分类: C/C++
2006-08-01 16:49:37
// Module Name: tcpserver.cpp
//
// Description:
//
// This sample illustrates how to develop a simple TCP server application
// that listens for a TCP connection on port 5150 and receives data. This
// sample is implemented as a console-style application and simply prints
// status messages when a connection is accepted and when data is received
// by the server.
//
// Compile:
//
// cl -o tcpserver tcpserver.cpp ws2_32.lib
//
// Command Line Options:
//
// tcpserver.exe
//
// NOTE: There are no command parameters.
//
#include
#include
void std_err(int type);
void main(void)
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen;
int Port = 10001;
int Ret;
char DataBuffer[1024];
char ReceBuffer[1024];
int lastErr;
// Initialize Winsock version 2.2
if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
{
// NOTE: Since Winsock failed to load we cannot use WSAGetLastError
// to determine the error code as is normally done when a Winsock
// API fails. We have to report the return status of the function.
printf("WSAStartup failed with error %d\n", Ret);
return;
}
// Create a new socket to listening for client connections.
if ((ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
== INVALID_SOCKET)
{
lastErr = WSAGetLastError();
std_err(lastErr);
WSACleanup();
return;
}
// Setup a SOCKADDR_IN structure that will tell bind that we
// want to listen for connections on all interfaces using port
// 5150. Notice how we convert the Port variable from host byte
// order to network byte order.
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Associate the address information with the socket using bind.
if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr))
== SOCKET_ERROR)
{
lastErr = WSAGetLastError();
std_err(lastErr);
closesocket(ListeningSocket);
WSACleanup();
return;
}
// Listen for client connections. We used a backlog of 5 which is
// normal for many applications.
if (listen(ListeningSocket, 5) == SOCKET_ERROR)
{
lastErr = WSAGetLastError();
std_err(lastErr);
closesocket(ListeningSocket);
WSACleanup();
return;
}
printf("We are awaiting a connection on port %d.\n", Port);
// Accept a new connection when one arrives.
while (1)
{
//if ((NewConnection = accept(ListeningSocket, (SOCKADDR *) &ClientAddr,&ClientAddrLen)) == INVALID_SOCKET)
if ((NewConnection = accept(ListeningSocket, NULL,NULL)) == INVALID_SOCKET)
{
lastErr = WSAGetLastError();
std_err(lastErr);
closesocket(ListeningSocket);
WSACleanup();
return;
}
printf("We successfully got a connection from %s:%d.\n",
inet_ntoa(ClientAddr.sin_addr), ntohs(ClientAddr.sin_port));
// At this point you can do two things with these sockets. Await
// for more connections by calling accept again on ListeningSocket
// and start sending or receiving data on NewConnection. For
// simplicity We will stop listening for more connections by closing
// ListeningSocket. We will start sending and receiving data on
// NewConnection.
//closesocket(ListeningSocket);
// Start sending and receiving data on NewConnection. For simplicity,
// we will just receive some data and report how many bytes were
// received.
printf("We are waiting to receive data...\n");
memset(DataBuffer, 0, sizeof(DataBuffer));
memset(ReceBuffer, 0, sizeof(DataBuffer));
if ((Ret = recv(NewConnection, DataBuffer, sizeof(DataBuffer), 0))
== SOCKET_ERROR)
{
lastErr = WSAGetLastError();
std_err(lastErr);
closesocket(NewConnection);
WSACleanup();
return;
}
printf("We successfully received %d byte(s).\n", Ret);
sprintf(ReceBuffer, "Receive: %s.\n", DataBuffer);
printf("We successfully received %s.\n", ReceBuffer);
closesocket(NewConnection);
}
// For this application we do not plan to do anything else with the
// connection so we will just close the connection.
printf("We are now going to close the client connection.\n");
closesocket(NewConnection);
closesocket(ListeningSocket);
// When your application is finished handling the connections
// call WSACleanup.
WSACleanup();
}
void std_err(int type) {
char *error;
switch(type) {
case 10004: error = "Interrupted system call"; break;
case 10009: error = "Bad file number"; break;
case 10013: error = "Permission denied"; break;
case 10014: error = "Bad address"; break;
case 10022: error = "Invalid argument (not bind)"; break;
case 10024: error = "Too many open files"; break;
case 10035: error = "Operation would block"; break;
case 10036: error = "Operation now in progress"; break;
case 10037: error = "Operation already in progress"; break;
case 10038: error = "Socket operation on non-socket"; break;
case 10039: error = "Destination address required"; break;
case 10040: error = "Message too long"; break;
case 10041: error = "Protocol wrong type for socket"; break;
case 10042: error = "Bad protocol option"; break;
case 10043: error = "Protocol not supported"; break;
case 10044: error = "Socket type not supported"; break;
case 10045: error = "Operation not supported on socket"; break;
case 10046: error = "Protocol family not supported"; break;
case 10047: error = "Address family not supported by protocol family"; break;
case 10048: error = "Address already in use"; break;
case 10049: error = "Can't assign requested address"; break;
case 10050: error = "Network is down"; break;
case 10051: error = "Network is unreachable"; break;
case 10052: error = "Net dropped connection or reset"; break;
case 10053: error = "Software caused connection abort"; break;
case 10054: error = "Connection reset by peer"; break;
case 10055: error = "No buffer space available"; break;
case 10056: error = "Socket is already connected"; break;
case 10057: error = "Socket is not connected"; break;
case 10058: error = "Can't send after socket shutdown"; break;
case 10059: error = "Too many references, can't splice"; break;
case 10060: error = "Connection timed out"; break;
case 10061: error = "Connection refused"; break;
case 10062: error = "Too many levels of symbolic links"; break;
case 10063: error = "File name too long"; break;
case 10064: error = "Host is down"; break;
case 10065: error = "No Route to Host"; break;
case 10066: error = "Directory not empty"; break;
case 10067: error = "Too many processes"; break;
case 10068: error = "Too many users"; break;
case 10069: error = "Disc Quota Exceeded"; break;
case 10070: error = "Stale NFS file handle"; break;
case 10091: error = "Network SubSystem is unavailable"; break;
case 10092: error = "WINSOCK DLL Version out of range"; break;
case 10093: error = "Successful WSASTARTUP not yet performed"; break;
case 10071: error = "Too many levels of remote in path"; break;
case 11001: error = "Host not found"; break;
case 11002: error = "Non-Authoritative Host not found"; break;
case 11003: error = "Non-Recoverable errors: FORMERR, REFUSED, NOTIMP"; break;
case 11004: error = "Valid name, no data record of requested type"; break;
default: error = strerror(errno); break;
}
fprintf(stderr, "\nError: %s\n", error);
//exit(1);
}