简体   繁体   English

使用TCP套接字将文件发送到多个客户端

[英]send a file to multiple clients using TCP socket

I'm developing a web application which waits for N (say, around 5) users to connect to a webservice via a TCP socket. 我正在开发一个Web应用程序,它等待N个用户(例如大约5个)通过TCP套接字连接到Web服务。 The server keeps track of the number of sockets connected, and once it reaches N he then sends a (single) file, say up to 2MB, to all of them simultaneously. 服务器跟踪连接的套接字的数量,一旦达到N,他便会同时向所有套接字发送一个(单个)文件,例如2MB。 The emphasis here is on timing - they should all receive the file at the same time, rather than one after the other. 这里的重点是时间-他们都应该同时接收文件,而不是一个接一个地接收。

As a newbie to c# and socket programming, I wish to know what would be the best approach in this case? 作为C#和套接字编程的新手,我想知道在这种情况下最好的方法是什么? I thought of the following: The server (asynchronously) receives socket connections and once it reaches N, loops through all of the bytes in the file, and on each iteration sends a single Kbyte (or maybe less?) to each one of the clients connected - this, in my opinion, is the closest way to sending a file simultaneously. 我想到了以下几点:服务器(异步)接收套接字连接,一旦到达N,便遍历文件中的所有字节,并在每次迭代中向每个客户端发送一个Kbyte(或更少)?连接-在我看来,这是同时发送文件的最接近方法。

I'm kind of confused about how to implement this. 我对如何实现这一点感到困惑。 Any help would be great. 任何帮助都会很棒。 Thanks 谢谢

EDIT: by receiving at the same time I meant, technically, that I don't want the server sending the file to the first client, then to the second, then to the third etc, but rather send it to all of them at once, once it's out of the server, it's out of my hands! 编辑:通过同时接收,我的意思是,从技术上来说,我不希望服务器将文件发送到第一个客户端,然后发送到第二个客户端,再发送到第三个客户端,而是一次将其发送给所有客户端,一旦它从服务器中移出,它就不在我手中! Assuming there are no network problems, and the clients are all very near (physically), they should receive the file more or less at the same time. 假设没有网络问题,并且客户端都非常近(物理上),则它们应该同时或多或少地接收文件。 maybe the solution is simpler than I thought... 也许解决方案比我想象的要简单...

You already plan to accept socket connections asynchronously and since a callback occurs on a separate thread, you could simply have an async callback that: 您已经计划异步接受套接字连接,并且由于回调发生在单独的线程上,因此您可以简单地拥有一个异步回调,该回调:

  • accepts the incoming socket connection 接受传入的套接字连接
  • calls BeginAccept() again (on the listening socket) 再次(在侦听套接字上)调用BeginAccept()
  • sends the file 发送文件
  • closes the connection (of the previously accepted socket) 关闭(先前接受的套接字的)连接

If multiple clients connect at once, this will result in multiple threads sending the file concurrently, and almost at the same time. 如果多个客户端同时连接,这将导致多个线程几乎同时同时发送文件。

Your file may be accessed by multiple threads at once, so you'll have to for instance open it with FileShare.Read . 您的文件可能同时被多个线程访问,因此您必须使用FileShare.Read打开它。

Hope this helps, I ignored the "N simultaneous clients" as I understand this is not really a requirement. 希望这会有所帮助,我忽略了“ N个并发客户”,因为我知道这并不是必须的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM