在C#和socketprogramming中使用api [英] using api in c# and socketprogramming

查看:96
本文介绍了在C#和socketprogramming中使用api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#和套接字编程中使用api?请.

How can use api in c# and socket programming? please.

推荐答案

让我们假设您对套接字有个完全的了解,否则很难解释任何东西.尽管似乎一开始很难找到,但在.NET中如何使用套接字的想法很简单.

您将需要使用:
Let''s assume you have the very idea of sockets, otherwise it would be hard to explain anything. The ideas of how to use sockets in .NET are simple enough, even though the seem to be hard to find -- at first.

You will need to use:
using Sockets = System.Net.Sockets;
using Threads = System.Threading;
using Streams = System.IO;
using IPAddress = System.Net.IPAddress;



现在,确实是什么样的插座?首先,您需要选择UDP与TCP.无论如何,要使用的顶级类是:Sockets::TcpListenerSockets::TcpClientSockets::UdpClient. UdpClient更简单,但是业务逻辑"可能要困难得多.因为我无法教您自己的业务逻辑,所以让我们专注于TCP;和UDP,您以后可以自己学习. TCP是套接字的最典型用法,而UDP可以保留给更多奇特的应用程序.

您的通信层的所有设计都可以基于六个简单的想法来构建:


想法#1 :使用TCP,您可以处理会话和频道.对于每个会话,网络上的一台主机扮演服务器的角色,另一台角色扮演客户端的角色.哪一方读取或写入数据都没有关系(通常,双方都使用代码定义的应用程序级协议).重要的是谁正在侦听新连接是服务器.假设一侧只有一台服务器,另一侧只有一个客户端.然后,您基本上将需要在服务器端使用两个单独的线程:一个正在侦听新连接,另一个正在一次从所有客户端套接字读取数据/向所有客户端套接字写入数据.每个远程套接字有单独的线程通常是一个大错误:如果线程太多,该怎么办? -结果不可预测(例如服务器崩溃).

注意:没有严格的确切配方,每个主机上的进程都扮演服务器或客户端的角色:每个进程可以实现一台以上的服务器和一个以上的客户端.因此,我举了最简单的例子.我们将只关注两侧的两个插槽和相关的螺纹(请参见上文).

想法#2 :服务器套接字的创建方式如下:



Now, what kind of sockets, indeed? First, you need to choose from UDP vs. TCP. Anyway, top classes to use are: Sockets::TcpListener, Sockets::TcpClient, Sockets::UdpClient. UdpClient is more simple, but "business logic" could be much more difficult. As I cannot teach you your own business logic, let''s concentrate on TCP; and UDP you can learn later by yourself. TCP is the most typical use of sockets, while UDP can be reserved for much more exotic applications.

All the design of your communication layer could be built around six simple ideas:


Idea #1: With TCP you work with sessions and channels. For each session, one host on your network plays the role of server, another -- the role of client. It does not matter which side is reading or writing data (typically, both sides, using some application-level protocol you define by your code). What does matter is who is listening for a new connection is the server. Let''s assume there are just one server on one side and one client on another. Then you will basically need two separate threads on server side: one is listening for new connections, another one is reading/writing data from/to all client sockets at once. Having separate threads for each remote sockets is usually a big mistake: what if there are too many of them? -- the result unpredictable (like server crash).

Note: There is not strict exact recipe which process on each host plays the role of server or client: each can implement more then one server and more than one client. Therefore, I pick up the most simple example; we shall concentrate just on two sockets on both sides and associated threads (see above).

Idea #2: Server socket is created like this:

Server = new Sockets::TcpListener(IPAddress.Any, port);
Server.ExclusiveAddressUse = true;



请注意使用IPAddress.Any:服务器不知道其自己的IP或远程套接字IP.
现在,重要的是要理解在两个线程之间使用相同的TcpListener实例.不需要IPC原语来互锁此实例:最初,套接字被设计为本身用作IPC(但是,通常,您通常需要使用互斥体来互锁对共享数据的访问).

想法#3 :服务器的侦听线程应在无限循环中使用以下调用:



Note use of IPAddress.Any: server does not know its own IP or remote socket IPs.
Now, it is important to understand that the same instance of TcpListener is used across two threads. No IPC primitive are needed to interlock this instance: initially sockets are designed to serve as IPC themselves (but you usually will need to use mutexes to interlock access to shared data, as always).

Idea #3: Server''s listening thread should use the following call in an infinite loop:

Sockets::TcpClient client = Server.AcceptTcpClient();



此调用是阻塞调用,因此线程将真正在等待连接的过程中处于休眠状态,而不会浪费单个CPU周期.

此处的变量client表示服务器套接字上的远程客户端套接字.该对象应在服务器的通信线程上使用,以写入或读取数据.由于我们不知道期望有多少远程连接,因此所有此类对象都应收集在某个容器中(我将使用 Queue< Sockets :: TcpClient> )使用在按顺序读取/写入数据时.

想法#4 :服务器的通信线程应运行无限循环,以对作为
获得的线程进行读取和/或写入.



This call is a blocking one, so the thread will be truly sleeping in waiting for a connection, not wasting a single CPU cycle.

The variable client here represents remote client socket on server''s socket. This object should be used on communication thread of the server to write or read the data. As we don''t know how many remote connection to expect, all such objects should be collected in some container (I would use Queue<Sockets::TcpClient>) to be used in reading/writing the data in sequence.

Idea #4: The server''s communication thread should run an infinite cycle reading and/or writing to thread obtained as

NetworkStream stream = client.GetStream();



想法5 :客户端上的客户端线程首先连接到选定的远程服务器(由URL和端口选择),然后进行无限循环读和/或写操作,以与该操作对称的顺序对移除套接字进行写操作.在服务器上实施的订单:服务器写,客户端读,反之亦然.相当好的策略是通过一些确认码(例如一个特殊字节)来确认在一个方向上发送的每个数据块:



Idea #5: Client thread on client side first connects to selected remote server (selected by URL and port) then goes to infinite cycle reading and/or writing to/from remove socket in the order symmetrical to the order implemented on the server: server writes, client reads and visa versa. Pretty good policy is to confirm each chunk of data send in one direction by some confirmation code (like one special byte):

Client = new Sockets::TcpClient();
Client.ExclusiveAddressUse = false;
//...try block...
Client.Connect(PublisherHostName, Port);
// loop, try block, etc...
Streams::Stream Stream = Client.GetStream();
// read/write to/from Stream (it represents remote server's stream after connection



最后的想法#6 :
现在的麻烦是:流读/写操作使用字节数组,但是您想使用一些对象.可能的解决方案之一:使用System.Runtime.Serialization二进制格式程序-请参见序列化说明,System.SerializableAttribute和相关主题.

哦!为什么我还在写?基本上就是这样.

稍后,我希望获得一些反馈.有帮助吗?也许需要更详细的文章.

谢谢您的关注.



Last idea #6:
Now the trouble is: Stream read/write operations work with arrays of byte, but you want to use some objects instead. One of the possible solutions: use System.Runtime.Serialization binary formatter -- see the description of serialization, System.SerializableAttribute and related topics.

Oh! Why I''m still writing? That''s it, basically.

I would like some feedback later on. Does it help? Maybe, more detailed article is needed.

Thank you for attention.


这篇关于在C#和socketprogramming中使用api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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