

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


int result; WSADATA WsaDat; result=WSAStartup(MAKEWORD(1, 1), &WsaDat) ;
if (result!= 0) cout<<"WSA Initialization failed";
SOCKET Socket; Socket = socket(AF_INET, SOCK_STREAM, 0);
if (Socket == INVALID_SOCKET) cout<<"Socket creation failed";
4. Binding Socket
//declaring SOCKETADDR instance SOCKADDR_IN SockAddr;
//We want to use port 50 SockAddr.sin_port = 50;
//We want an internet type connection (TCP/IP) SockAddr.sin_family = AF_INET;
//We want to listen on IP address 127.0.0. //I'll give a few better ways to set thi // s value later SockAddr.sin_addr.S_un.S_un_b.s_b1 = 127; SockAddr.sin_addr.S_un.S_un_b.s_b2 = 0;
Note : Variable of type SOCKETADDR_IN is created instead of SOCKETADDR, the reason is that struct SOCKADD_IN holds the same information in the same way as struct SOCKADDR does, the difference is that struct SOCKADDR_IN is easier to work with.
SockAddr.sin_addr.S_un.S_un_b.s_b3 = 0; SockAddr.sin_addr.S_un.S_un_b.s_b1 = 1;
result=bind(Socket, (SOCKADDR *)(&SockAddr), sizeof(SockAddr)); //attempting to bind
if (result== SOCKET_ERROR) cout<<"Attempt to bind failed"; //SOCKET_ERROR is a pre-defined constant
5. Listening Connections
listen(Socket, 1);
6. Accepting Connections
SOCKET TempSock = SOCKET_ERROR; //declaring temporary socket while (TempSock == SOCKET_ERROR) TempSock = accept(Socket, NULL, NULL); //Accept will return error if there is no connection Socket = TempSock; //The loop breaks when a connection is accepted, // copying it to original socket
7. Sending Data
Now that we have a server with a connected client they need to exchange information. This is done exactly the same for the client as it is for the server. The functions to use are send() and recv(). They both take four parameters the socket to send on, the data to send, and the number of bytes in the data. The way they expect the data is in a pointer to a char
char String[50]; result= send(Socket, String, 50, 0); if (result==0) cout<<"Connection closed at other end."; else cout<<”Data sent = “<<String<<endl;
8. Receiving Data
result= recv(Socket, String, 50, 0); if (result==0) cout<<"Connection closed at other end."; else