Sunday, August 29, 2010

server client and socket programming-C++

Server:
1)Establish a listening socket and wait for connections from clients.
2)Accept the client's connection attempt.
3)Send and receive data.
4) Close the connection.



Client:
 1) Create a client socket and attempt to connect to server.
2) Send and receive data.
3) Close the connection.

File Download site 
Makefile: Makefile for this project
Socket.h:  define Socket class and declare server  function  create, bind, listen, accept client function: connect, data function send, recv
SocketException.h: define SocketException class to deal with
class method fail. If a class method fails for any reason, it throws an exception of type SocketException.
SeverSocket.h:   define SeverSocket class derived from Socket class, redefine accept method and  define overloaded the << and >> operators, so that when used, they wrote data to and read data from the socket.
ClientSocket.h: define ClientSocket class derived from Socket class,
define overloaded the << and >> operators, so that when used, they wrote data to and read data from the socket.
Socket.cpp, ServerSocket.cpp and Client.Socket.cpp detaily define
methods declared in header file
simple_server_main.cpp:  a simple implementation of a server
The new_sock variable contains all of our socket information, so we use it to exchange data with the client. The line "new_sock >> data;" should be read as "read data from new_sock, and place that data in our string variable 'data'." Similarly, the next line sends the data in 'data' back through the socket to the client.


If you're paying attention, you'll notice that what we've created here is an echo server. Every piece of data that gets sent from the client to the server gets sent back to the client as is. We can write the client so that it sends a piece of data, and then prints out the server's response:
simple_client_main.cpp: a simple implementation of a client
We send the string "Test Message." to the server, read the response from the server, and print out the response to std output. 

No comments:

Post a Comment