在C#中,可以使用Socket.ReceiveTimeout属性来设置读取数据的超时时间。设置该属性后,如果在指定时间内没有接收到数据,客户端会抛出SocketException异常。

为了禁止客户端在读取数据超时期间反复发送数据,可以在客户端发送数据之前,先判断之前是否已经发送了数据并且还未接收到响应。如果是,则等待一段时间再发送,否则直接发送数据。

以下是示例代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Client {
    private Socket clientSocket;

    public Client() {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }

    public void Connect(string ip, int port) {
        IPAddress ipAddress = IPAddress.Parse(ip);
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

        clientSocket.Connect(remoteEP);
    }

    public void Send(string message) {
        if (clientSocket == null || !clientSocket.Connected) {
            throw new Exception("Not connected to server.");
        }

        // 判断是否已经发送了数据并且还未接收到响应
        if (clientSocket.Available > 0) {
            // 等待1秒再发送
            System.Threading.Thread.Sleep(1000);
        }

        byte[] data = Encoding.ASCII.GetBytes(message);
        clientSocket.Send(data);

        // 设置读取数据超时时间为5秒
        clientSocket.ReceiveTimeout = 5000;

        try {
            byte[] buffer = new byte[1024];
            int bytesRead = clientSocket.Receive(buffer);
            string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received: {0}", response);
        } catch (SocketException ex) {
            if (ex.SocketErrorCode == SocketError.TimedOut) {
                Console.WriteLine("Receive timeout.");
            } else {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
    }

    public void Disconnect() {
        if (clientSocket != null && clientSocket.Connected) {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
}

在上述代码中,当客户端发送数据时,会先判断是否已经有未处理的响应数据。如果有,则等待1秒再发送数据。同时,设置读取数据超时时间为5秒,如果在指定时间内没有接收到响应数据,会抛出SocketException异常并输出“Receive timeout.”

C#TCP异步读取TCP服务器数据读取数据超时期间禁止客户端反复发送数据

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

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