You must Sign In to post a response.
  • Category: .NET

    How to connect single client to multiple server?

    I want to connect single client to multiple servers . now my client able to connect to one server only. I think program needs to create one socket and one thread per server and port is common for all server. I found some examples regarding this but not found some in c#. Help me to find some links or examples.
  • #761095
    From the question, what i got is u want to connect to more than one sql server at a time. you can do it by different connection strings. but u can have connection to one server at one time. do the calculations and save to one db, then pass the variable to another db later
    Do Good... Enjoy your life.....

  • #761097
    Its not sql server, Its client server Socket program.

  • #761099
    ok. then am sorry...
    Do Good... Enjoy your life.....

  • #761105
    Hello Priyanka,

    As i have sent you some example projects. Refer this below code for your multiple server connection :

    Server.cs :

    using System;
    using System.Net.Sockets;
    using System.Threading;
    public class AsynchIOServer
    {
    static TcpListener tcpListener = new TcpListener(10);

    static void Listeners()
    {

    Socket socketForClient = tcpListener.AcceptSocket();
    if (socketForClient.Connected)
    {
    Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
    NetworkStream networkStream = new NetworkStream(socketForClient);
    System.IO.StreamWriter streamWriter =
    new System.IO.StreamWriter(networkStream);
    System.IO.StreamReader streamReader =
    new System.IO.StreamReader(networkStream);
    while (true)
    {
    string theString = streamReader.ReadLine();
    Console.WriteLine("Message recieved by client:" + theString);
    if (theString == "exit")
    break;
    }
    streamReader.Close();
    networkStream.Close();
    streamWriter.Close();
    //}

    }
    socketForClient.Close();
    Console.WriteLine("Press any key to exit from server program");
    Console.ReadKey();
    }

    public static void Main()
    {
    //TcpListener tcpListener = new TcpListener(10);
    tcpListener.Start();
    Console.WriteLine("************This is Server program************");
    Console.WriteLine("Hoe many clients are going to connect to this server?:");
    int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
    for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
    {
    Thread newThread = new Thread(new ThreadStart(Listeners));
    newThread.Start();
    }
    }
    }


    Client.cs :

    using System;
    using System.Net.Sockets;
    using System.Threading;
    public class Client
    {
    static public void Main(string[] Args)
    {
    TcpClient socketForServer;
    try
    {
    socketForServer = new TcpClient("localHost", 10);
    }
    catch
    {
    Console.WriteLine(
    "Failed to connect to server at {0}:999", "localhost");
    return;
    }

    NetworkStream networkStream = socketForServer.GetStream();
    System.IO.StreamReader streamReader =
    new System.IO.StreamReader(networkStream);
    System.IO.StreamWriter streamWriter =
    new System.IO.StreamWriter(networkStream);
    Console.WriteLine("*******This is client program who is connected to localhost on port No:10*****");

    try
    {
    string outputString;
    Console.WriteLine("type:");
    string str = Console.ReadLine();
    while (str != "exit")
    {
    streamWriter.WriteLine(str);
    streamWriter.Flush();
    Console.WriteLine("type:");
    str = Console.ReadLine();
    }
    if (str == "exit")
    {
    streamWriter.WriteLine(str);
    streamWriter.Flush();

    }
    }
    catch
    {
    Console.WriteLine("Exception reading from Server");
    }
    // tidy up
    networkStream.Close();
    Console.WriteLine("Press any key to exit from client program");
    Console.ReadKey();
    }

    private static string GetData()
    {
    //Ack from sql server
    return "ack";
    }
    }


    Hope this will help you.
    Mark the answer if it helped you.

    Regards,
    Nirav Lalan
    DNS Gold Member
    "Failure is the path of least persistence"

  • #761109
    This program connects to only one server. i want to connect client to more than one server. I attached here my sample form image. in which i want to do is that ,
    1 . when I write ip and port and start client button client needs to connect to that server .

    2 . When i again write ip and port and click start client button client again connect to another server without closing connect with first server.

    and when this client connects with server it shows in below txtbox hence when server connects it shows correct server info.
    hence both servers connected to that client. i just can do client program to connect to multiple server because server is a device.

    Delete Attachment

  • #761110
    See this document.

    clientform.docx

    Delete Attachment

  • #761111
    Hello Priyanka,

    As i worked in Console Application. For windows forms application i have sent you the sample project for socket programming. You can work on it by using this code that i have mentioned above.

    Hope you will be successful.

    Regards,
    Nirav Lalan
    DNS Gold Member
    "Failure is the path of least persistence"

  • #761115
    I made code for this and its working fine and receiving messages but after connecting to 2 servers it receives messg from both servers but it receives message from 1stly connected server only one time and
    from
    2ndly connected server it receives continuously.

    why this happens i cant get it. here is my code.
    please check it,

    Socket clsock;

    private void button1_Click(object sender, EventArgs e)
    {
    Thread th = new Thread(() => StartClient());
    th.Start();
    }

    public void StartClient()
    {
    try
    {
    clsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    int port = Convert.ToInt32(txtport.Text);
    IPAddress ip = IPAddress.Parse(txtip.Text);
    clsock.Connect(ip, port);
    counter += 1;
    AppendlblData(Convert.ToString(counter) + " Server Connected " + clsock.RemoteEndPoint + Environment.NewLine);
    Thread th = new Thread(() => ReceiveData());
    th.Start();
    }
    catch { }
    }

    public void ReceiveData()
    {
    try
    {
    for (int i = 0; i >= 0; i++)
    {
    byte[] data = new byte[128];
    clsock.Receive(data);
    string dataReceived = Encoding.ASCII.GetString(data);
    char[] c = { '*', '$', '!', '@' };

    if (dataReceived != null)
    {
    string res = dataReceived.TrimStart(c);
    MessageBox.Show(res);
    // SendKeys.SendWait(res);
    }
    }
    }
    catch(Exception es)
    {
    MessageBox.Show(es.Message);
    }
    }

  • #761136
    Hai Priyanka,
    As I know that one time, you can connect with one server only.
    if you are using multiple ip addresses, you can connect to the server asynchronously so that one server will be connected and made it idle and other will be active.
    Not sure whether it will be helpful, but you can see the below link for more details:

    http://stackoverflow.com/questions/26578748/how-connect-multi-client-to-multi-server-in-c-sharp

    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #761138
    my client program as i posted above able to connect to 2 server with diff ip and port. but receives messages 1 time from first server and multiple times from newly connected server but i want to receive messages from both servers mutiple times


Sign In to post your comments