Friday, January 25, 2008

[Programming] Quick guide for network programming (2)

Source code for Server's socket:


#include <winsock2.h>
#include <stdio.h>

void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );
// call WSAStartup, initialize winsock.dll and negotiate the socket version
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
// Tell the user that we could not find a usable WinSock DLL.
return;
}


if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
// Tell the user that we could not find a usable WinSock DLL.
WSACleanup( );
return;
}

// a) create a socket
SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);
// b) bind
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); // INADDR_ANY use any IP address of the host, you can use inet_addr("127.0.0.1"); to designate a specific IP
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6123); // use a port number larger than 1024
bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
// c) listen
listen(sockSrv, 5);
// d) accept
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while(1) // waiting for requests from clients
{
SOCKET sockConn = accept(sockSrv, (SOCKADDR *)&addrClient, &len); // create a new socket for this connection
// e) send/recv
char sendBuff[100];
sprintf(sendBuff, "Welcome %s to server", inet_ntoa(addrClient.sin_addr));
send(sockConn, sendBuff, strlen(sendBuff)+1, 0);

char recvBuff[100];
recv(sockConn, recvBuff, 100, 0);
printf("%s\n", recvBuff);
// f) close the current socket and wait for another request
closesocket(sockConn); //release the socket for this connection
}

}



Source code for Client's Socket programming:


#include <winsock2.h>
#include <stdio.h>

void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );
// call WSAStartup, initialize winsock.dll and negotiate the socket version
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
// Tell the user that we could not find a usable WinSock DLL.
return;
}


if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
// Tell the user that we could not find a usable WinSock DLL.
WSACleanup( );
return;
}
// a) create a socket
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
// b) connect
SOCKADDR_IN addrClient;
addrClient.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // loopback address
addrClient.sin_family = AF_INET;
addrClient.sin_port = htons(6123);
connect(sockClient, (SOCKADDR *)&addrClient, sizeof(SOCKADDR));
// c) send/recv
char recvBuff[100];
recv(sockClient, recvBuff, 100, 0);
printf("%s\n", recvBuff);
send(sockClient, "This is from client B", strlen("This is from client B")+1, 0);

// d) close
closesocket(sockClient);
WSACleanup();
}

1 comment:

SBL Software Solutions said...

Thank you for the code guide!

Regards
SBL Software Development Solutions
http://www.sblsoftware.com/gis-software.aspx