Click here to Skip to main content
15,910,234 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new in .net socket programming. I need three application and they will be in both client and server mode.
case 1 :Application 1(client mode) send request to application 2(server mode) and application 2(now client mode) process the request and send this request to application 3(server mode) then application 3 process the request and send response to the application 2 and application 2 process this response and send to the application 1.

case 2 :Application 3(client mode) send request to application 2(server mode) and application 2(now client mode) process the request and send this request to application 1(server mode) then application 1 process the request and send response to the application 2 and application 2 process this response and send to the application 3.

case 3 : Application 2 always check the connection with application 1 and application 3 and vice versa.

For this purpose i have tried the following code for case 1.For the first request it work fine and then does not work correctly.How to implement the applications?

Application 1(Client mode):
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TCP.Client.ConsoleApplication
{
   public class Client
    {
       TcpClient tcpClientObj;
       public Client()
       {
           this.tcpClientObj = new TcpClient();
           Thread clientThread = new Thread(ConnectToServer);
           clientThread.Start();
       }

       public void ConnectToServer()
       {
           IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
           tcpClientObj.Connect(serverEndPoint);
           Console.WriteLine("Connected");           
           
           while (true)
           {
               Console.Write("Request To Server: ");
               String message = Console.ReadLine();
               Stream streamObj = tcpClientObj.GetStream();

               ASCIIEncoding asciiEncodingObj = new ASCIIEncoding();
               byte[] byteValueOfMessage = asciiEncodingObj.GetBytes(message);
               streamObj.Write(byteValueOfMessage, 0, byteValueOfMessage.Length);

               byte[] recievedFromServer = new byte[100];
               int k = streamObj.Read(recievedFromServer, 0, 100);

               string recivedMessageFromServer = string.Empty;
               for (int i = 0; i < k; i++)
               {
                   recivedMessageFromServer += Convert.ToChar(recievedFromServer[i]);
               }

               Console.WriteLine("Response From Server: " + recivedMessageFromServer);
               streamObj.Flush();
           }
       }
    }
}


Application 2:(Server and Client mode)
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TCP.Server.ConsoleApplication
{
    public class Server
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public static Hashtable clientsList = new Hashtable();
        public Server()
        {
             IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
             this.tcpListener = new TcpListener(ipAddress, 8001);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
        private void ListenForClients()
        {
            this.tcpListener.Start();

            Console.WriteLine("MW is running at port 8001...");
            Console.WriteLine("MW  End point is  :" + tcpListener.LocalEndpoint);
            Console.WriteLine("Waiting for TWO connection.....");
            int counter = 0;

            while (true)
            {
                counter += 1;

                TcpClient client = this.tcpListener.AcceptTcpClient();
                Console.WriteLine("I am listening for TWO connections on " +
                                                IPAddress.Parse(((IPEndPoint)tcpListener.LocalEndpoint).Address.ToString()) +
                                                 "on port number " + ((IPEndPoint)tcpListener.LocalEndpoint).Port.ToString());
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
               clientThread.Start(client);
            }
        }

        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[tcpClient.ReceiveBufferSize];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }
                ASCIIEncoding encoder = new ASCIIEncoding();

                Console.WriteLine("Request From TWO: " + encoder.GetString(message, 0, bytesRead));
                clientStream = tcpClient.GetStream();
                byte[] buffer = SendRequestToCBS(message);// encoder.GetBytes(responseMessage);
                clientStream.Write(buffer, 0, buffer.Length);

                clientStream.Flush();
            }

            tcpClient.Close();
        }

        private byte[] SendRequestToCBS(byte[] message)
        {
            TcpClient clientCbs = new TcpClient();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
            clientCbs.Connect(serverEndPoint);
            Console.WriteLine("Connected To CBS");
            while (true)
            {
                Console.Write("Request To CBS: ");
                Stream streamObj = clientCbs.GetStream();

                ASCIIEncoding asciiEncodingObj = new ASCIIEncoding();

                streamObj.Write(message, 0, message.Length);

                byte[] recievedFromServer = new byte[100];
                int k = streamObj.Read(recievedFromServer, 0, 100);

                string recivedMessageFromServer = string.Empty;
                for (int i = 0; i < k; i++)
                {
                    recivedMessageFromServer += Convert.ToChar(recievedFromServer[i]);
                }

                Console.WriteLine("Response From CBS: " + recivedMessageFromServer);
                streamObj.Flush();
                return recievedFromServer;
            }
        }

        }

    }


Application 3:(Server mode)
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TCP.ServerCBS.ConsoleApplication
{
    public class ServerCbs
    {
        
        private TcpListener tcpListener;
        private Thread listenThread;

        public static Hashtable clientsList = new Hashtable();
        public ServerCbs()
        {
             IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
             this.tcpListener = new TcpListener(ipAddress, 3000);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
        private void ListenForClients()
        {
            this.tcpListener.Start();

            Console.WriteLine("CBS is running at port 3000...");
            Console.WriteLine("CBS End point is  :" + tcpListener.LocalEndpoint);
            Console.WriteLine("Waiting for a MW connection.....");
            int counter = 0;

            while (true)
            {
                counter += 1;
                TcpClient client = this.tcpListener.AcceptTcpClient();
                Console.WriteLine("I am listening for MW connections on " +
                                                IPAddress.Parse(((IPEndPoint)tcpListener.LocalEndpoint).Address.ToString()) +
                                                 " on port number " + ((IPEndPoint)tcpListener.LocalEndpoint).Port.ToString());
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
               clientThread.Start(client);
            }
        }

        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }
                ASCIIEncoding encoder = new ASCIIEncoding();
                Console.WriteLine("Request From MW: " + encoder.GetString(message, 0, bytesRead));             
                clientStream = tcpClient.GetStream();
                Console.Write("Response To Client: ");

                String responseMessage = Console.ReadLine();

                byte[] buffer = encoder.GetBytes(responseMessage);
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }

            tcpClient.Close();
        }

    
    }
}
Posted
Updated 30-Nov-15 16:04pm
v2

1 solution

You have misunderstood how sockets and/or client/server architecture works.

A Client can Send and Receive streams from a server.

A Server can Send and Receive multiple streams from multiple Clients.


There are other problems i see with this immediately that make this not worth doing:

How does each "Server" sync its contents with the others?
How do clients that are connected to different servers interact?
What is your actual reasoning for requiring multiple "servers"?


case 2 :Application 3(client mode) send request to application 2(server mode) and 
application 2(now client mode) process the request and send this request to 
application 1(server mode) then application 1 process the request and send response to 
the application 2 and application 2 process this response and send to the  
application 3. 



What you have just described is a single Server/Client relationship.

Client 1 Sends new information to Server.
Server Stores Information.
Client 2 Asks Server for updated information.
Server Hands Out Information.
Client 2 Updates Information on Server.
Server Stores Information.
Client 1 Asks Server for updated information.
Server Hands out Information.
etc, etc.


Edit: On a side note, To do what you're actually requesting will require ALOT more code than that, Actually thinking about it is quite painful.
 
Share this answer
 
v6
Comments
Md. Shihab Uddin 30-Nov-15 22:49pm    
Application 2 is a middle ware
1. it receive request from application 1 and after process send this request to application 3, application 3 response for this request to application 2, then application 2 process this response and send back the response to the application 1
2. it receive request from application 3 and after process send this request to application 1, application 1 response for this request to application 2, then application 2 process this response and send back the response to the application 3
[no name] 30-Nov-15 22:51pm    
No, You're just calling a server Middleware and ignoring how it actually works. What you are describing is 1 Server with multiple clients.
Md. Shihab Uddin 30-Nov-15 22:55pm    
for that case how can i solve it?
[no name] 30-Nov-15 22:58pm    
Client 1 Sends new information to Server.
Server Stores Information.
Client 2 Asks Server if it has new information from any client or a specific client.
Server Hands Out Information.
Client 2 Updates information and gives it back to Server.
Server Stores Information.
Client 1 Asks Server if it has new information from any client or a specific client.
Server Hands out Information. etc etc.
Md. Shihab Uddin 1-Dec-15 11:24am    
Please give me solution link or sample example code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900