Tuesday, June 17, 2014

C# - Server Client application


Today I want to show a short tutorial about a server client communication via TCP/IP.
The server is able to handle more than one client at the same time.


Let´s start with the Server.

Server Program:


Create a new Console program.



First we create a new function StartServer();



Start Server












Due to that the server should listen to his own IP address, I´ve prepared a separate function for this.



















Within the function StartServer() we are creating a new TcpListener and calling the function WaitForClientConnect().


In WaitForClientConnect() we are handling all connections to the server.
Therefore we will start for every new connected client a new thread.
This will allow us, if a connection takes very long, the main program is still able to accept new requests.
























In OnClientConnect() we are creating a new object type of TcpClient for every new client and call the class HandleClientRequest.

Then we can start the communication with clientReq.StartClient();




In the class HandleClientRequest the Initialize looks like following:














We will use the TcpClient from the main program.
The StartClient() function is reading the message from the client and afterwards the function is going in a waiting mode.

The message process looks like following:


































In WaitForRequest() we are starting to read the message by using the function ReadCallback.
The function ReadCallback will send, after proceeding, the message back to the client.


At least we finish the server program by implementing the StartServer() function in the Main part.








Client Programm:


We also create a Console program.

First we create a new class TCPClient.
The class contains following functions:
  • ConnectToServer
  • ClosConnection
  •  SendData
  • ReceiveData




Funktion ConnectToServer:













Here we create a new object type of TcpClient.
Replace Server IP with the IP address from the server.



Funktion CloseConnection:






Here we are closing the active connection.



Funktion SendData:












Converts the message into a byte array and sends this array to the server.
(On server side this will end in the function ReadCallback)



Funktion ReceiveData:



























This function could be called after SendData and will receive the answer from the server.
Also this answer message will be converted from a byte array into a string message.



The whole flow for the client program looks like following:




No comments:

Post a Comment