1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <winsock2.h>
#include <iostream>
using namespace std;
int main()
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int Port = 5150;
int ClientAddrLen;
char data[80];
int bufLen = 80;
int ret;
// Initialize Winsock version 2.2
WSAStartup(MAKEWORD(2,2), &wsaData);
// Create a new socket to listen for client connections.
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Set up 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.
ret = bind(ListeningSocket, (SOCKADDR *)&ServerAddr,
sizeof(ServerAddr));
cout << sizeof(ServerAddr) << '\n';
// Listen for client connections. We used a backlog of 5, which
// is normal for many applications.
ret = listen(ListeningSocket, 5);
// Accept a new connection when one arrives.
NewConnection = accept(ListeningSocket, (SOCKADDR *)
&ClientAddr,&ClientAddrLen);
if (NewConnection == SOCKET_ERROR)
{
cout << "WSACleanup failed with error " << WSAGetLastError() << '\n';
}
// At this point you can do two things with these sockets. Wait
// for more connections by calling accept again on ListeningSocket
// and start sending or receiving data on NewConnection. We will
// describe how to send and receive data later in the chapter.
data[0] = 'W';
data[1] = '\0';
ret = send(NewConnection, data, bufLen, 0);
// When you are finished sending and receiving data on the
// NewConnection socket and are finished accepting new connections
// on ListeningSocket, you should close the sockets using the
// closesocket API. We will describe socket closure later in the
// chapter.
closesocket(NewConnection);
closesocket(ListeningSocket);
// When your application is finished handling the connections,
// call WSACleanup.
WSACleanup();
return 0;
}
|