该代码定义了一个名为'SUser'的类,位于'UdpClientDemo_Server'命名空间下。该类主要用于管理与客户端之间的 TCP 通信。

构造函数

该类有两个构造函数:

  1. SUser(Action<String> ShowMsg, String remoteIP, int remotePort)
  • 接收一个 Action<String> 类型的委托 ShowMsg,用于显示接收到的消息。
  • 接收一个字符串类型的远程客户端 IP 地址 remoteIP
  • 接收一个整数类型的远程客户端端口号 remotePort
  • 使用 TcpClient 对象连接到远程客户端。
  • 使用 BinaryWriterBinaryReader 对象对网络流进行读写操作。
  1. SUser(Action<String> ShowMsg, TcpClient remote_client)
  • 接收一个 Action<String> 类型的委托 ShowMsg,用于显示接收到的消息。
  • 接收一个已有的 TcpClient 对象 remote_client
  • 使用已有的 TcpClient 对象的网络流进行读写操作。

私有方法

  • StartJS()
    • 在后台创建一个新的任务(Task)来接收来自客户端的消息。
    • 使用 BinaryReaderReadString 方法读取消息。
    • 使用 ShowMsg 委托将消息显示在用户界面上。
    • 如果在读取消息时发生异常,说明客户端已经掉线,将会显示一条提示消息,并跳出循环。

公共方法

  • Send(String str)
    • 用于向客户端发送消息。
    • 接收一个字符串类型的参数 str
    • 使用 BinaryWriter 对象将消息写入网络流。

代码示例

namespace UdpClientDemo_Server
{
    internal class SUser
    {
        TcpClient locaClient;
        Action<String> ShowMsg;
        BinaryWriter bw;
        BinaryReader br;
        public SUser(Action<String> ShowMsg, String remoteIP, int remotePort)
        {
            this.ShowMsg = ShowMsg;
            locaClient = new TcpClient();
            locaClient.Connect(remoteIP, remotePort);
            NetworkStream ns = locaClient.GetStream();
            bw = new BinaryWriter(ns);
            br = new BinaryReader(ns);

            StartJS();

        }
        public SUser(Action<String> ShowMsg, TcpClient remote_client)
        {
            this.ShowMsg = ShowMsg;
            locaClient = remote_client;//!!!!!!!!!!
            NetworkStream ns = locaClient.GetStream();
            bw = new BinaryWriter(ns);
            br = new BinaryReader(ns);
        }
        private void StartJS()
        {
            String remoteEp = locaClient.Client.RemoteEndPoint.ToString();

            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        String sss = br.ReadString();
                        ShowMsg(remoteEp + '>' + sss);
                    }
                    catch
                    {
                        ShowMsg('服务端掉线了!');
                        break;
                    }

                }
            });
        }
        public void Send(String str)
        {
            bw.Write(str);
        }
    }
}

注意

  • 该代码仅供参考,实际应用中可能需要进行调整和完善。
  • 该代码中使用 BinaryWriterBinaryReader 对象进行网络数据读写,这是一种比较常用的方法。但是,也可以根据具体需求使用其他方法,例如使用 StreamWriterStreamReader 对象。
  • 该代码中使用 Task.Run 方法启动了一个新的任务,用于接收来自客户端的消息。这是一种异步操作,可以提高程序的性能。但是,在使用异步操作时需要注意线程安全问题。
  • 该代码中使用了一个 Action<String> 类型的委托 ShowMsg,用于显示接收到的消息。可以使用其他类型的委托,例如 Func<String, String> 类型,来实现更复杂的处理。
C# SUser 类:使用 TCP 协议实现客户端通信

原文地址: http://www.cveoy.top/t/topic/cU0q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录