简体   繁体   English

无论客户端发生什么情况,我如何让服务器程序继续运行?

[英]How can I make a server program keep running no matter what happens to a client?

Take a look at the following two programs: 看看以下两个程序:

//Server

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.Tasks;

namespace MyServerProgram
{
    class Program
    {
        static void Main(string[] args)
        {            
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            int port = 2000;
            TcpListener listener = new TcpListener(ip, port);
            listener.Start();

            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Connected " + ((IPEndPoint)client.Client.RemoteEndPoint).Address);


            NetworkStream netStream = client.GetStream();

            BinaryReader br = new BinaryReader(netStream);

            try
            {
                while (client.Client.Connected)
                {
                    string str = br.ReadString();

                    Console.WriteLine(str);
                }
            }
            catch (Exception ex)
            {
                var inner = ex.InnerException as SocketException;
                if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
                    Console.WriteLine("Disconnected");
                else
                    Console.WriteLine(ex.Message);

                br.Close();
                netStream.Close();
                client.Close();
                listener.Stop();
            }
        }
    }
}


//Client

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.Tasks;

namespace MyClientProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 2000;
            TcpClient client = new TcpClient("localhost", port);

            NetworkStream netStream = client.GetStream();

            BinaryWriter br = new BinaryWriter(netStream);

            try
            {
                int i=1;
                while (client.Client.Connected)
                {
                    br.Write(i.ToString());
                    br.Flush();
                    i++;

                    int milliseconds = 2000;
                    System.Threading.Thread.Sleep(milliseconds);
                }
            }
            catch
            {
                br.Close();
                netStream.Close();
                client.Close();
            }
        }
    }
}

The problem I am facing with the Server is, the Server program exits as soon as the client is closed. 我面临服务器的问题是,一旦客户端关闭,服务器程序就会退出。

I want the server program to keep running no matter what a client does or happens to it. 我希望无论客户端做什么或发生什么,服务器程序都会继续运行。

How can I do that? 我怎样才能做到这一点?

Try putting a while loop around your AcceptTcpClient (and associated logic). 尝试在AcceptTcpClient(及相关逻辑)周围放置一个while循环。 To paraphrase from your server code: 从您的服务器代码中解释:

boolean keepRunning = true;
while (keepRunning) {
  TcpClient client = listener.AcceptTcpClient();
  Console.WriteLine("Connected ...") // and other stuff deleted.

  // while client connected...
      string str = br.ReadString();
      // check to see if we should continue running.
      keepRunning = ! "quit".equalsIgnoreCase(str);
  // Other stuff

Note this is very insecure - any client regardless of where / who they are could terminate your server be sending a "quit" message to your server. 请注意,这是非常不安全的 - 任何客户端无论在何处/谁可以终止您的服务器都会向您的服务器发送“退出”消息。 In real life, you would probably require a more strict mechanism. 在现实生活中,您可能需要更严格的机制。 Obviously with this mechanism, you will need your client to be able to generate the "quit" message text when you need it to do so. 显然,使用此机制,您将需要您的客户端能够在需要时生成“退出”消息文本。

Another method is to run the whole server in a Thread. 另一种方法是在Thread中运行整个服务器。 Then in another thread, have a method that an operator could use to close the server (eg a menu selection in a Swing Application). 然后在另一个线程中,有一个操作员可以用来关闭服务器的方法(例如Swing应用程序中的菜单选择)。

There are plenty of options you could choose from to "manage" the shutdown. 您可以选择许多选项来“管理”关机。

Also, as written, your code is single threaded. 另外,如上所述,您的代码是单线程的。 That is, it will wait for a client to connect, deal with that client and then exit (or if you apply the keepRunning while loop modification wait for the next client to connect). 也就是说,它将等待客户端连接,处理该客户端然后退出(或者如果你应用keepRunning while while循环修改等待下一个客户端连接)。 But, only one client can connect to this server at any one time. 但是,任何时候只有一个客户端可以连接到此服务器。

To make it multi-threaded (can service multiple clients at one time), put the body of your server (the service code) into a Thread and invoke a new instance of the Thread to serve that client. 要使其成为多线程(可以同时为多个客户端提供服务),请将服务器主体(服务代码)放入线程并调用线程的新实例来为该客户端提供服务。 After starting the service Thread, the main loop simply waits for the next client to connect. 启动服务线程后,主循环只是等待下一个客户端连接。 Thus, your main loop will become something like this: 因此,您的主循环将变为如下所示:

while (keepRunning) {
    TcpClient client = listener.AcceptTcpClient();
    Console.WriteLine("Connected ...") // and other stuff deleted.

    ServiceThread st = new ServiceThread(client);
    st.start ();
}

and the Service Thread will be something like: 和服务线程将是这样的:

public class ServiceThread extends Thread {
  private TcpClient client;
  public ServiceThread (TcpClient client) {
    this.client = client;
  }
  @override
  public void run() {
    NetworkStream netStream = client.GetStream();
    BinaryReader br = new BinaryReader(netStream);
    try {
            while (client.Client.Connected) {
            // Stuff deleted for clarity
            }
         }
        catch (Exception ex) {
            // Exception handling stuff deleted for clarity.
        }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在客户端连接到服务器后立即打印通知? - How can I make a server print a notification as soon as a client connects to it? 如何在TCP服务器多客户端对话中创建线程 - how can I make thread in TCP server multi client dialogue 如何在客户端保持与Web服务的会话? - How can I keep the session with the webservice at client? 如何保持异步程序运行? - How to keep an asynchronous program running? 如何确保程序在Windows Server 2012上的所有会话中仅运行一次? - How do I make sure a program is only running once across all sessions on a windows server 2012? 当 iPhone 用户退出主屏幕或 App Switcher 时,如何让我的计时器继续运行? - How can I make my timer keep running when the iPhone user quits to the home screen or the App Switcher? 我如何使功能继续进行 - How can i make the function keep going 如何使运行在Azure实例中的ASP.NET WebAPI程序每分钟更新一次数据库? - How can I make an ASP.NET WebAPI program running in an Azure instance update a database every minute? 从客户端在服务器内存上运行程序 - Running a Program on Server Memory from Client 如何让我的客户端 - 服务器应用程序成为多客户端服务器应用程序? C# - How can i make my client-server app a multiclient-server app? C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM