在C#中发送一些限制客户端从服务器 [英] Sending some constraints to client from server in C#

查看:102
本文介绍了在C#中发送一些限制客户端从服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用在C#套接字编程一个简单的服务器将从客户端接收文件。我的示例代码段如下。



我想补充一些限制。我想打一个限制文件大小(如4  KB或2  KB)以及将尽快发送到客户端允许的文件格式(如.doc,txt文件,的.cpp等)客户端连接到服务器,这样客户端可以相应地发送文件。 ?如何做到这一点。



示例代码段:

 使用系统; 
使用System.Collections.Generic;使用System.Net
;使用的System.Net.Sockets
;
:使用System.IO;
使用System.Text;

命名文件传输
{
类节目
{
静态无效的主要(字串[] args)
{
//监听端口1234

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

Console.WriteLine(服务器开始);

//无限循环连接到新客户
,而(真)
{
//接受TcpClient的
的TcpClient的TcpClient = tcpListener.AcceptTcpClient( );
Console.WriteLine(连接到客户端);
字节[]数据=新的字节[1024];
的NetworkStream NS = tcpClient.GetStream();
INT的recv = ns.Read(数据,0,data.Length);
StreamReader的读者=新的StreamReader(tcpClient.GetStream());

//将增加一些线路加限制...

}
}
}
}

我将有哪些附加行添加到代码的限制发送到客户端?


< DIV CLASS =h2_lin>解决方案

基本上,我觉得主要是你需要两样东西:




  • 定义应用协议在其他的答案建议


  • 和处理部分的读/写




有关处理部分读取(不知道需要多少这样的功能),你可以使用函数像的 //www.yoda.arachsys.com/csharp/readbinary.html相对=nofollow>

 公共静态无效ReadWholeArray(流流,字节[]数据)
{
INT偏移= 0;
INT剩余= data.Length;
而(剩余&0)
{
INT读= stream.Read(数据,偏移,剩余的);
如果(读< = 0)
抛出新EndOfStreamException
(的String.Format(与{0}字节留给达到读取流的末尾,剩下的));其余
- =读;
偏差+ =读;
}
}



事情是传统的流。阅读()并不能保证你告诉它,在另一方面,这种方法读取的字节数,将保证已经阅读在指定数据的字节数。长度参数。所以你可以使用这样的功能来实现所需的应用协议而不是



<子>对这类应用协议的一些相关资料,你会发现的这里



< HR>

确定这是例子,如何在服务器可以发送文件长度的限制和文件扩展名:

  //发送串
串EXT =.TXT;
字节[] = textBytes Encoding.ASCII.GetBytes(EXT);
ns.Write(textBytes,0,textBytes.Length);

//现在,送整 - 文件长度的限制参数
INT上限= 333;
字节[] = intBytes BitConverter.GetBytes(限制);
ns.Write(intBytes,0,intBytes.Length); //发送整型 - 介意字节顺序



但你仍然需要某种协议,否则你应该让客户端读取完全流,以后就未必了解析这些数据,这是不平凡的,如果数据没有固定的长度等等 - ?不然怎么会在客户区分该消息的一部分是文本,其中整数


I have created a simple server using socket programming in C# which will receive a file from the client side. My sample code segment is given below.

I want to add some restrictions. I want to make a limit on the file size (such as 4 KB or 2 KB) and allowable file formats (such as .doc, .txt, .cpp, etc.) which will be sent to the client as soon as the client connects to the server so that the client can send files accordingly. How will I do that?

Sample code segment:

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...

            }
        }
    }
}

Which additional lines will I have to add to the code to send the restrictions to client?

解决方案

Basically I think mainly you need two things:

  • define application protocol as suggested in other answer

  • and handle partial read/writes

For handling partial reads (not sure how much such function is needed for write) you may use function like 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;
    }
}

Thing is traditional Stream.Read() doesn't guarantee to read as many bytes as you told it, this method on the other hand, will ensure to have read as many bytes as specified in data.Length parameter. So you can use such function to implement the desired application protocol instead.

Some relevant information about such application protocols you will find here too


Ok this is for example how the server could send file length limit and the file extension:

// 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

But you will still need some kind of protocol otherwise you should let client read the "full" stream and parse these data later somehow, which isn't trivial if the data doesn't have fixed length etc - otherwise how will the client distinguish which part of the message is text, which integer?

这篇关于在C#中发送一些限制客户端从服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆