• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 525
  • Last Modified:

Connect to multiple Tcp Servers


I want to connect to multiple TCP/IP servers at the same time.(Different IPs, same port)

When there is one server  my code is like:
TcpClient = new TcpClient()
client.GetStream().BeginRead(readBuffer, 0, 1024, newAsyncCallback(GetFromServer), null);

Now for multiple servers do i need to create  a TcpClient list ? Do i need to worry about thread safety ?

Frankly i could not decide how to design.
  • 2
1 Solution
To connect to multiple servers at the same time, you need to create multiple TcpClient instances in a thread.

Folllowing is a model using threads:
public class ServerIno
            public string Address;

            // add any other server info here

        static void Main()
            List<ServerIno> listServerInfo = new List<ServerIno>();
            listServerInfo.Add(new ServerIno { Address = "" });

            for(int s=0; s < listServerInfo.Count; s++)
                Thread t = new Thread(DoWork);

        public static void DoWork(object data)
            ServerIno si = (ServerIno)data;

            int portNumber = 25; // use the correct port number here
            TcpClient client = new TcpClient(si.Address, portNumber);

            // use client object to send messages to server and get response from server here

Open in new window


Above sample doesn't need to do anything special for thread safety. But depending on further requirement (that will make threads to update a shared variable), then you need to consider thread-safetry issues.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now