【问题标题】:How to connect multiple client to single server in C#如何在 C# 中将多个客户端连接到单个服务器
【发布时间】:2015-12-23 07:18:02
【问题描述】:

我有两个应用程序,一个是 tcpclient,另一个是 tcp 服务器。我将字符串作为数据从 tcpclient 发送到 tcp 服务器。在单个客户端的情况下一切正常,但是当我尝试从不同的机器运行另一个客户端时,我收到异常“远程主机强制关闭连接”请帮助我如何将多个客户端连接到单个 tcp 服务器这是我的代码。

/*TCP SERVER*/
   static void Main(string[] args)
        {
            //192.168.0.105
            IPAddress ipAd = IPAddress.Parse("192.168.0.100");
        // use local m/c IP address, and 
        // use the same in the client
            FileStream f = File.Open("D:/GPSResearchandDevelopment/GPSService/GPSService/abc.txt", FileMode.OpenOrCreate);
            IAsyncResult a = null;
            connection:
            Console.WriteLine("reCHED TO THE CONNECTION");

            TcpListener myList = new TcpListener(ipAd, 8001);


            myList.Start();


            Console.WriteLine("The server is running at port 8001...");
            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");

            Socket s = myList.AcceptSocket();

            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);

            Console.WriteLine("Recieved...");

            a = f.BeginWrite(b, 0, b.Length, null, null);
            f.EndWrite(a);

            String[] str = Encoding.UTF8.GetString(b).Split('|');
            for (int i = 0; i < str.Length; i++)
                Console.WriteLine(str[i]);

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");

            //s.Close();
            myList.Stop();

            goto connection;


        }
/*TCP CLIENT*/

 static void Main(string[] args)
        {
        CONNECTAGAIN:
            TcpClient tcpclnt = new TcpClient();

            Console.WriteLine("Connecting.....");


            tcpclnt.Connect("192.168.0.100", 8001);
            // use the ipaddress as in th1e server program

            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");

            String str = Console.ReadLine();
            //String str = "supriya|laxman|medankar";
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");

            stm.Write(ba, 0, ba.Length);

            byte[] bb = new byte[100];
            int k = stm.Read(bb, 0, 100);

            for (int i = 0; i < k; i++)
            {
                Console.Write(Convert.ToChar(bb[i]));


            }

            tcpclnt.Close();
//            Console.ReadLine();
            goto CONNECTAGAIN;
        }

【问题讨论】:

  • 您想同时进行多个连接吗?在这种情况下,您需要一些并行运行的线程来接受传入的连接尝试。
  • 简而言之,您需要为每个客户端创建和维护一个套接字和线程。您编写的代码一次只允许一个连接。接收调用应该在单独的线程上进行,因为它是一个阻塞调用。
  • 是的,我想要多个连接@同时

标签: c# network-programming


【解决方案1】:

基本上主线程应该做的大部分是

create a server socket //TcpListener mylist

while(true)
    listen for new connection and create a client socket //Socket s
    spawn thread to handle client socket connection

您应该将生成的线程封装在一个类中,这样您就可以将套接字存储为一个成员,以便于访问和清理。

您生成/创建的线程应该运行与客户端交互的逻辑。

即。所有这些代码。

 Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);

            Console.WriteLine("Recieved...");

            a = f.BeginWrite(b, 0, b.Length, null, null);
            f.EndWrite(a);

            String[] str = Encoding.UTF8.GetString(b).Split('|');
            for (int i = 0; i < str.Length; i++)
                Console.WriteLine(str[i]);

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");

            //s.Close();
            myList.Stop();

如果您这样做,您可以独立于其他客户端之间的交互持续侦听新的客户端连接。

【讨论】:

    【解决方案2】:

    你可以在tcpclient的地方使用socket

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2023-03-09
      • 2015-10-06
      • 2015-06-13
      相关资源
      最近更新 更多