c# - 在 C# 中从服务器向客户端发送一些约束

标签 c# sockets

我已经使用 C# 中的套接字编程创建了一个简单的服务器,它将从客户端接收一个文件。下面给出了我的示例代码段。

我想添加一些限制。我想限制发送给客户端的文件大小(例如 4 KB 或 2 KB)和允许的文件格式(例如 .doc、.txt、.cpp 等)连接到服务器,以便客户端可以相应地发送文件。我将如何做到这一点?

示例代码段:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace FileTransfer
{
    class Program
    {
        static void Main(string[] args)
        {
            // Listen on port 1234

            TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
            tcpListener.Start();

            Console.WriteLine("Server started");

            //Infinite loop to connect to new clients
            while (true)
            {
                // Accept a TcpClient
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                                Console.WriteLine("Connected to client");
                byte[] data = new byte[1024];
                NetworkStream ns = tcpClient.GetStream();
                int recv = ns.Read(data, 0, data.Length);
                StreamReader reader = new StreamReader(tcpClient.GetStream());

               //Will add some lines to add restrictions...

            }
        }
    }
}

我必须在代码中添加哪些附加行才能将限制发送给客户端?

最佳答案

基本上我认为你主要需要两件事:

  • 按照其他答案中的建议定义应用程序协议(protocol)

  • 并处理部分读/写

为了处理部分读取(不确定write 需要多少这样的函数)你可以使用像below 这样的函数:

public static void ReadWholeArray (Stream stream, byte[] data)
{
    int offset=0;
    int remaining = data.Length;
    while (remaining > 0)
    {
        int read = stream.Read(data, offset, remaining);
        if (read <= 0)
            throw new EndOfStreamException 
                (String.Format("End of stream reached with {0} bytes left to read", remaining));
        remaining -= read;
        offset += read;
    }
}

传统的 Stream.Read() 不保证读取您告诉它的字节数,另一方面,此方法将确保读取指定的字节数data.Length 参数。因此,您可以使用此类函数来实现所需的应用程序协议(protocol)。

您会发现有关此类应用程序协议(protocol)的一些相关信息here也是


好的,这是服务器如何发送文件长度限制和文件扩展名的示例:

// Send string
string ext = ".txt";
byte [] textBytes = Encoding.ASCII.GetBytes(ext);
ns.Write(textBytes, 0, textBytes.Length); 

// Now, send integer - the file length limit parameter
int limit = 333;
byte[] intBytes = BitConverter.GetBytes(limit);
ns.Write(intBytes, 0, intBytes.Length); // send integer - mind the endianness

但是你仍然需要某种协议(protocol),否则你应该让客户端读取“完整”流并稍后以某种方式解析这些数据,如果数据没有固定长度等,这不是微不足道的 - 否则如何客户端区分消息的哪一部分是文本,哪一部分是整数?

关于c# - 在 C# 中从服务器向客户端发送一些约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34298012/

相关文章:

c# - 如何在微服务之间共享领域事件方案?

c# - 如何在 C# 中将此功能编写为通用扩展方法?

Java - 客户端从服务器接收空白消息,但仅通过网络

Java InputStream 自动拆分套接字消息

java - 关于 ServerSocket,需要澄清

c# - 如何使用 SQLite-Net 扩展建立 A -> B -> C 关系

c# - 在启动 TCP 服务器之前如何优雅地启动 C# TCP 客户端

c# - Path.GetFilename - 尝试从目录中获取文件名

python - 限制 SSL 连接的带宽

java - 如何使客户端-服务器 Java 应用程序在一个端口上发送消息但在另一个端口上接收消息?