Visual C++ - Introduction to Socket Programming
Sockets are very important for establishing communication between the server and client. A socket can be a raw socket or TCP streaming socket or a datagram socket.
Here is the sample code for client application that connects to the server and sends the data.
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(s == -1)
AfxMessageBox("Socket Initialiation Error");
struct hostent *hostentry;
int portno = 80;
bool bSent = false;
hostentry = gethostbyname("www.google.com");
char *pipaddr = inet_ntoa (*(struct in_addr *)*hostentry->h_addr_list);
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(portno);
serveraddr.sin_addr.s_addr = inet_addr(pipaddr);
//serv_addr.sa_data = htons(portno);
if (connect(s,(SOCKADDR*)&serveraddr,sizeof(SOCKADDR_IN)) < 0)
AfxMessageBox("ERROR connecting to the server");
char sbuf = "Data", rbuf;
recv(s, rbuf, 1024, 0);
send(s, sbuf, strlen(sbuf), 0);
The main difference for server side sockets are that will use bind command to bind with the address and use listen command for accepting the incoming connection. Usually binding and listen part is implemented from the main thread and when there is an incoming connection, the client connection established by creating a new thread. The child thread is responsible for serving the clients request.
The datagram sockets use sendto and recvfrom functions for communication. I will create a sample fro datagram sockets in the near future and post it to this site shortly.