如何让服务器在客户端连接到它时立即打印通知?

How can I make a server print a notification as soon as a client connects to it?

看看下面两个程序:

//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();

            NetworkStream netStream = client.GetStream();

            BinaryReader br = new BinaryReader(netStream);

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

                    Console.WriteLine(str);
                }
            }
            catch
            {
                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();
            }
        }
    }
}

这些程序运行良好。

假设,在这个程序的这一点上,我需要服务器在客户端连接到它时立即在屏幕上打印一条消息,并且在客户端断开连接时也是如此。

我该怎么做?

AcceptTcpClient 阻塞执行并开始等待连接。所以在它之后你可以写消息给客户端connected。你也可以写连接的客户端地址。仅供参考,但有时可能会有帮助。

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

对于检测客户端断开连接,您可以捕获异常。像这样更改您的 catch

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