C#实现TCP客户端服务器应用程序的最佳方法 [英] C# best way to implement TCP Client Server Application

查看:153
本文介绍了C#实现TCP客户端服务器应用程序的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展我对.NET框架的经验,并希望构建一个客户端/服务器应用程序.实际上,客户端/服务器是小型销售点系统,但首先,我想重点介绍服务器与客户端之间的通信.将来,我想使其成为WPF应用程序,但现在,我只是从控制台应用程序开始.

I want to extend my experience with the .NET framework and want to build a client/server application. Actually, the client/server is a small Point Of Sale system but first, I want to focus on the communication between server and client. In the future, I want to make it a WPF application but for now, I simply started with a console application.

2个功能:

  • 个客户接收一个数据集,并每15/30分钟更新一次更改价格/新产品的更新
    (因此,代码将在带有Thread.sleep的Async方法中运行15/30分钟).

  • client(s) receive(s) a dataset and every 15/30min an update with changed prices/new products
    (So the code will be in a Async method with a Thread.sleep for 15/30 mins).

在关闭客户端应用程序时,发送一种报告(例如xml)

when closing the client application, sending a kind of a report (for example, an xml)

在互联网上,我发现了很多示例,但是我无法确定哪种方法是最好/最安全/性能最佳的工作方式,因此我需要一些建议,以建议应采用哪些技术.

On the internet, I found lots of examples but i can't decide which one is the best/safest/performanced manner of working so i need some advice for which techniques i should implement.

客户端/服务器

我想要1个服务器应用程序,最多可处理6个客户端.我读到线程使用大量的mb,也许更好的方法是具有异步/等待功能的任务.

I want 1 server application that handles max 6 clients. I read that threads use a lot of mb and maybe a better way will be tasks with async/await functionallity.

带有ASYNC/AWAIT的示例

http://bsmadhu.wordpress.com/2012/09/29/simplify-asynchronous-programming-with-c-5-asyncawait/

带有THREADS的示例

mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/

mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/

SOCKETS示例

codereview.stackexchange.com/questions/5306/tcp-socket-server

codereview.stackexchange.com/questions/5306/tcp-socket-server

这似乎是套接字的一个很好的例子,但是,由于并非所有类都包括在内,因此修订后的代码无法完全正常工作msdn.microsoft.com/zh-CN/library/fx6588te(v=vs.110).aspxMSDN的这个示例在Buffersize和消息结尾的信号方面有很多其他功能.我不知道这是否是旧方法",因为在我之前的示例中,他们只是将字符串从客户端发送到服务器,仅此而已.

This seems to be a great example of sockets, however, the revisioned code isn't working completely because not all the classes are included msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx This example of MSDN has a lot more with Buffersize and a signal for the end of a message. I don't know if this just an "old way" to do this because in my previous examples, they just send a string from the client to the server and that's it.

.NET FRAMEWORK REMOTING/WCF 我还发现了有关.NET和WCF远程处理部分的信息,但不知道是否需要实现这一点,因为我认为Async/Await的示例还不错.

.NET FRAMEWORK REMOTING/ WCF I found also something about the remoting part of .NET and WCF but don' know if I need to implement this because i think the example with Async/Await isn't bad.

序列化对象/数据集/XML

在它们之间发送数据的最佳方法是什么?使用XML序列化程序还是仅使用二进制文件?

What is the best way to send data between it? Juse an XML serializer or just binary?

数据集示例-> XML

stackoverflow.com/questions/8384014/convert-dataset-to-xml

stackoverflow.com/questions/8384014/convert-dataset-to-xml

具有远程处理功能的示例

akadia.com/services/dotnet_dataset_remoting.html

akadia.com/services/dotnet_dataset_remoting.html

如果我应该使用Async/Await方法,那么在服务器应用程序中是否可以执行以下操作:

If I should use the Async/Await method, is it right to something like this in the serverapplication:

        while(true)
        {
            string input = Console.ReadLine();
            if(input == "products")
                SendProductToClients(port);
            if(input == "rapport")
            {
                string Example = Console.ReadLine();
            }                                
        }

考虑到现代系统上可用的RAM数量,

推荐答案

线程并不十分昂贵,因此,我认为优化线程数少并没有帮助.尤其是当我们谈论的是1个线程和2-5个线程之间的差异时.(在成百上千个线程中,线程的开销开始变得很重要.)

Threads are not terribly expensive, considering the amount of RAM available on modern systems, so I don't think it's helpful to optimize for a low thread count. Especially if we're talking about a difference between 1 thread and 2-5 threads. (With hundreds or thousands of threads, the cost of a thread starts to matter.)

但是您确实希望进行优化以最小化对您拥有的所有线程的阻塞.因此,例如,而不是使用Thread.Sleep以15分钟为间隔进行工作,而是设置一个计时器,让线程返回,并信任系统在15分钟后调用您的代码.并且,不要使用非阻塞操作,而不要阻塞用于通过网络读取或写入信息的操作.

But you do want to optimize for minimal blocking of whatever threads you do have. So for example instead of using Thread.Sleep to do work on 15 minute intervals, just set a timer, let the thread return, and trust the system to invoke your code 15 minutes later. And instead of blocking operations for reading or writing information over the network, use non-blocking operations.

async/await模式是.Net上异步编程的新热点,它是对始于.Net 1.0的Begin/End模式的重大改进.用async/await编写的代码仍在使用线程,它只是在使用C#和.Net的功能来向您隐藏很多复杂的线程-并且在大多数情况下,它隐藏了应该隐藏的内容,因此您可以将注意力集中在应用程序的功能上,而不是多线程编程的细节上.

The async/await pattern is the new hotness for asynchronous programming on .Net, and it is a big improvement over the Begin/End pattern that dates back to .Net 1.0. Code written with async/await is still using threads, it is just using features of C# and .Net to hide a lot of the complexity of threads from you - and for the most part, it hides the stuff that should be hidden, so that you can focus your attention on your application's features rather than the details of multi-threaded programming.

因此,我的建议是对所有IO(网络和磁盘)使用异步/等待方法,并使用计时器进行定期琐事,例如发送您提到的那些更新.

So my advice is to use the async/await approach for all of your IO (network and disk) and use timers for periodic chores like sending those updates you mentioned.

关于序列化...

XML相对于二进制格式的最大优点之一是,您可以将XML传输保存到磁盘中,并使用易于使用的工具将其打开,以确认有效载荷确实包含您认为会在其中的数据.因此,除非带宽不足,否则我倾向于避免使用二进制格式-即使那样,使用XML等文本友好格式开发大多数应用程序也是有用的,然后在发送和接收数据的基本机制变得充实之后切换到二进制格式

One of the biggest advantages of XML over binary formats is that you can save your XML transmissions to disk and open them up using readily-available tools to confirm that the payload really contains the data that you thought would be in there. So I tend to avoid binary formats unless bandwidth is scarce - and even then, it's useful to develop most of the app using a text-friendly format like XML, and then switch to binary after the basic mechanism of sending and receiving data have been fleshed out.

所以我的投票是针对XML的.

So my vote is for XML.

关于您的代码示例,那里没有异步/等待...

And regarding your code example, well ther's no async/await in it...

但是首先,请注意,典型的简单TCP服务器将具有一个小的循环,该循环侦听传入的连接并启动线程来处理每个新连接.然后,连接线程的代码将侦听传入的数据,对其进行处理并发送适当的响应.因此,新连接侦听"代码和单连接处理"代码是完全分开的.

But first, note that a typical simple TCP server will have a small loop that listens for incoming connections and starts a thread to hanadle each new connection. The code for the connection thread will then listen for incoming data, process it, and send an appropriate response. So the listen-for-new-connections code and the handle-a-single-connection code are completely separate.

因此,无论如何,连接线程代码可能看起来与您编写的代码相似,但您不仅可以调用ReadLine,还可以执行"string line = await ReadLine();"之类的操作.关键字await大约是您的代码允许一个线程退出(在调用ReadLine之后)然后在另一个线程上继续(当ReadLine的结果可用时)的位置.除非等待方法的名称以Async结尾,例如ReadLineAsync.从网络中读取一行文本并不是一个坏主意,但是您必须自己编写ReadLineAsync,并基于现有的网络API.

So anyway, the connection thread code might look similar to what you wrote, but instead of just calling ReadLine you'd do something like "string line = await ReadLine();" The await keyword is approximately where your code lets one thread exit (after invoking ReadLine) and then resumes on another thread (when the result of ReadLine is available). Except that awaitable methods should have a name that ends with Async, for example ReadLineAsync. Reading a line of text from the network is not a bad idea, but you'll have to write ReadLineAsync yourself, building upon the existing network API.

我希望这会有所帮助.

这篇关于C#实现TCP客户端服务器应用程序的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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