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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include<iostream>
#include"winsock.h"
#include<cstdio>
#include<cstdlib>
using namespace std;
#define NETWORK_ERROR -1
#define NETWORK_OK 0
int WINAPI WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lp,int n)
{
WSADATA ws;
int nret;
WSAStartup(0x0101,&ws);
SOCKET lsocket;
cout<<"\nCreating Socket .......";
lsocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(lsocket==INVALID_SOCKET)
{
cout<<"\nCould Not Creat Listening Socket.";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
else
cout<<"\nSocket Created......";
//Use a SOCKADDR_IN struct to fill addr info
SOCKADDR_IN serverinfo;
serverinfo.sin_family=AF_INET;
serverinfo.sin_addr.s_addr=inet_addr("127.0.0.1");
serverinfo.sin_port=htons(2609);
//Bind the socket to our local server addr
cout<<"\nBinding Socket .........";
nret=bind(lsocket,(SOCKADDR *)&serverinfo,sizeof(struct sockaddr));
if(nret==SOCKET_ERROR)
{
cout<<"\nCould Not Bind Listening Socket";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
else
cout<<"\nSocket Bound ..........";
//Make the bound socket listen.Up to 10 ma wait at any one time
cout<<"\nPutting Bound Socket to Listening Mode";
nret=listen(lsocket,10);
if(nret==SOCKET_ERROR)
{
cout<<"\nCould Not Attain Listen Mode";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
//Wait for client
cout<<"\nWaiting for Client .......";
SOCKET commsocket;
commsocket=accept(lsocket,NULL,NULL);
if(commsocket==INVALID_SOCKET)
{
cout<<"\nCould Not Setup Connection On Request";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
char sendbuffer[256]="\nServer : This is server,reporting on port 2609";
char recvbuffer[256];
nret=recv(commsocket,recvbuffer,255,0);
recvbuffer[nret]=0;
if(nret==SOCKET_ERROR)
{
cout<<"\nCould Not Hear Client";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
else
{
cout<<"\nClient : "<<recvbuffer;
nret=send(commsocket,sendbuffer,255,0);
if(nret==SOCKET_ERROR)
{
cout<<"\nCould Not Send Message to Client";
WSACleanup();
getchar();
return NETWORK_ERROR;
}
}
closesocket(commsocket);
closesocket(lsocket);
WSACleanup();
return NETWORK_OK;
}
| |