gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:54:51 25 4
gpt4 key购买 nike

看看下面两个程序:

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

关于c# - 如何让服务器在客户端连接到它时立即打印通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com