PDA

Click to See Complete Forum and Search --> : need help regarding Win api


ramforu
October 14th, 2005, 08:24 AM
i am student and i was asked to write a simple program using visual studio regarding socket programming.the description of the program is there should be a client and a server and server should reply to the client messeges.

please direct me what to use how to start writing the program

thanks
ram

warl0ck7
October 14th, 2005, 08:58 AM
Are you planning to use sockets? ,if yes The following should help:-

1. http://beej.us/guide/bgnet/
2. http://msdn.microsoft.com

frz
October 14th, 2005, 09:17 AM
whew. if i were you, check the socket programming section in msdn.microsoft.com

but anyway, i'll share with you my 2 cents-worth of idea on that area.

First, in your code, make sure you #include <winsock.h> (hehehe).

Second, before using any of those "socket" apis, you need to "initialize" the WSAStartup (please refer to microsoft msdn as to why you need to initialize this).


e.g.
if(WSAStartup(MAKEWORD(2,2), &ws) != NO_ERROR ){
return ERR_WSAStartup;
}


now if everythis is ok, create a "server" socket.


e.g.
SOCKET server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(server_socket == INVALID_SOCKET){
WSACleanup();
return ERR_INVALID_SOCKET;
}


if no error, then you need to "bind" the "server socket" like this:

// Bind server_socket
sockaddr_in s_in;
s_in.sin_family = AF_INET;
s_in.sin_addr.s_addr = inet_addr( "127.0.0.1" );
s_in.sin_port = htons(27401);

if ( bind( server_socket, (SOCKADDR*) &s_in, sizeof(s_in) ) == SOCKET_ERROR ) {
closesocket(server_socket);
WSACleanup();
return ERR_BIND_FAILED;
}


now if we're ok up to this point, then it's about time you need to start "listening" from "client" attempting to connect to the socket server. (hehehe)


// start eavesdropping on the socket.
if (listen( server_socket, 1 ) == SOCKET_ERROR ){
closesocket(server_socket);
WSACleanup();
return ERR_LISTEN_FAILED;
}


again, if we're ok up to this point then, you can send/receive data from server to the client.

// Accept client connection

SOCKET server_socket_accept;
BOOL isOk;
char welcome[]="Welcome.\r\n";
char szQuit[]="Connection closed.\r\n";

printf("Waiting for client to connect...");
isOk=true;

while(isOk){
server_socket_accept = accept(server_socket, NULL, NULL);
if(server_socket_accept == SOCKET_ERROR){
server_socket = server_socket_accept;
break;
}else{
printf("ok.\n");
if(send(server_socket_accept, welcome, strlen(welcome),0)==SOCKET_ERROR){
printf("Error sending message to client.\n");
closesocket(server_socket_accept);
isOk=false;
break;
}

}

// start receiving data from client

while(1){
// put your code or logic here. hehehe.....
}
}


anyway, there are lots of tutorial on the web on socket programming. so just check it out.