C# 如何使用套接字通过互联网发送数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/726115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:41:17  来源:igfitidea点击:

How can I send data over the internet using a socket?

c#socketsnetworking

提问by Mohanavel

I would like to send data over internet through a desktop application. I know a little bit about sockets. I have transferred the data within the LAN, but now I want to transfer the data over the internet. What is the best way to transfer both large and small quantities of data?

我想通过桌面应用程序通过互联网发送数据。我对套接字略知一二。我已经在局域网内传输了数据,但现在我想通过互联网传输数据。传输大量和少量数据的最佳方法是什么?

My system is connected to the server which has the access to the internet. My system's IP address is dynamic. I don't know how to send the data to another system which is connected to the internet. Do I need to find the router address? (My IP address is generated as 192.168.1.15).

我的系统连接到可以访问互联网的服务器。我的系统的 IP 地址是动态的。我不知道如何将数据发送到另一个连接到互联网的系统。我需要找到路由器地址吗?(我的 IP 地址生成为 192.168.1.15)。

Is using a socket enough, or is HTTP required?

使用套接字是否足够,或者是否需要 HTTP?

采纳答案by Sunny Milenov

Socket is enough if no firewalls/proxies are involved.

如果不涉及防火墙/代理,套接字就足够了。

But, as Internet is involved (not the fastest connection), I suggest for the sake of convenience you should better opt for remoting over http. That way, even if in the future the setup changes, and firewalls/proxies get involved in the equation, you should not worry.

但是,由于涉及 Internet(不是最快的连接),为了方便起见,我建议您最好选择通过 http 进行远程处理。这样,即使将来设置发生变化,并且防火墙/代理参与到等式中,您也不应该担心。

回答by paweloque

In your question you mix different things. Sockets are an abstraction for network communication. You will certainly need a socket to communicate over the network. However, possibly you will not see that a socket is used (like in a web-browser). Http is a communication protocol. This is what goes through a communication channel.

在你的问题中,你混合了不同的东西。套接字是网络通信的抽象。您肯定需要一个套接字来通过网络进行通信。但是,您可能不会看到使用了套接字(就像在 Web 浏览器中一样)。Http 是一种通信协议。这是通过通信渠道进行的。

回答by Vilx-

Visual Studio has a lot of well made facilities for creating and consuming SOAP XML Web Services. I'd look into it if I were you. Sure, there is some overhead, but coding against it is extremely easy.

Visual Studio 具有许多用于创建和使用 SOAP XML Web 服务的精心制作的工具。如果我是你,我会调查一下。当然,有一些开销,但是针对它进行编码非常容易。

Of course, I'm not sure how well that would scale if you had to transfer, say, tens or hundreads of megabytes of data across slow internet connections. It does offer asynchronous I/O, but I don't think you can get a progress indicator, and there most definately isn't a resume functionality.

当然,如果您必须通过慢速互联网连接传输数十或数百兆字节的数据,我不确定它的扩展性如何。它确实提供了异步 I/O,但我认为您无法获得进度指示器,而且绝对没有恢复功能。

Added:You can also continue using your socket. There is no extra work invloved for connecting to a server across the internet. Just specify the server's IP address, and away you go. Your OS will take care of all the gory details like routers, missing packets, etc.

补充:您也可以继续使用您的插座。通过 Internet 连接到服务器不需要额外的工作。只需指定服务器的 IP 地址,然后就可以了。您的操作系统将处理所有血腥细节,例如路由器、丢失的数据包等。

回答by Mystic

You can do it with .Net's Socket class or you can work with the more convenient TcpClient class.

您可以使用 .Net 的 Socket 类来实现,也可以使用更方便的 TcpClient 类。

Firstly though you need to figure out what server you intend to communicate with. Is it an HTTP server or an FTP server? Both HTTP and FTP are application-level protocols which are implemented on top of (using) sockets, which is really a transport layer interface.

首先,您需要弄清楚您打算与之通信的服务器。它是 HTTP 服务器还是 FTP 服务器?HTTP 和 FTP 都是在(使用)套接字之上实现的应用程序级协议,套接字实际上是一个传输层接口。

Your local IP address or the address of the router really doesn't matter. You however need to know the IP address of the remote host you intend to connect to. You can obtain this by calling:

您的本地 IP 地址或路由器地址真的无关紧要。但是,您需要知道要连接的远程主机的 IP 地址。您可以通过以下方式获得:

IPHostEntry host;

host = Dns.GetHostEntry(hostname);

You might also want to think about other issues when working with sockets, such as using timeouts to mask failure, the possibility of resuming upload/downloads when transferring large files, etc. If you spend sometime looking on the net, you should be able to find higher level HTTP/FTP apis that will let you work with file transfers much more easily.

在使用套接字时,您可能还想考虑其他问题,例如使用超时来屏蔽故障、传输大文件时恢复上传/下载的可能性等。如果您花一些时间在网上查看,您应该能够找到更高级别的 HTTP/FTP api,让您更轻松地处理文件传输。

Judging by your question, you seem pretty new to sockets, so reading thismight also help

从您的问题来看,您似乎对套接字很陌生,因此阅读本文也可能有所帮助

回答by bezieur

First you should make a decision what protocol you want to use TCP or UDP. Then you have two options: 1. use Socket (lower level) or 2. Use class like TCPClient or UDPClient (which represents a little higher abstraction. I'd suggest (for the begging the second option).

首先,您应该决定要使用 TCP 还是 UDP 的协议。然后你有两个选择:1. 使用 Socket(较低级别)或 2. 使用像 TCPClient 或 UDPClient 这样的类(代表更高的抽象。我建议(对于乞求第二个选项)。

回答by AndreasT

What you want to know depends heavily on many parts of your infrastructure.

您想知道什么在很大程度上取决于基础架构的许多部分。

If you want to send data to a server that is transparently connected to the internet, it is as easy as connecting to it's IP adress.

如果您想将数据发送到透明连接到互联网的服务器,就像连接到它的 IP 地址一样简单。

If you want to connect to some friend with a broadband connection, things get tricky. You usually have to configure both of your routers (or at least the target one) for NAT.

如果您想通过宽带连接连接到某个朋友,事情就会变得棘手。您通常必须为 NAT 配置两个路由器(或至少是目标路由器)。

Familiarize yourself with NAT, and the basics of IP routing. The details you provided are not sufficient to describe exactly what you want to do.

熟悉 NAT 和 IP 路由的基础知识。您提供的详细信息不足以准确描述您想要做什么。

回答by sipwiz

If all you want to do is transfer raw data from one machine to another it's very easy to do using a TCP socket.

如果您只想将原始数据从一台机器传输到另一台机器,那么使用 TCP 套接字非常容易。

Here's a quick example.

这是一个快速示例。

Server:

服务器:

 ThreadPool.QueueUserWorkItem(StartTCPServer);

 private static void StartTCPServer(object state) {
        TcpListener tcpServer = new TcpListener(IPAddress.Parse("192.168.1.15"), 5442);
        tcpServer.Start();
        TcpClient client = tcpServer.AcceptTcpClient();

        Console.WriteLine("Client connection accepted from " + client.Client.RemoteEndPoint + ".");

        StreamWriter sw = new StreamWriter("destination.txt");

        byte[] buffer = new byte[1500];
        int bytesRead = 1;

        while (bytesRead > 0) {
            bytesRead = client.GetStream().Read(buffer, 0, 1500);

            if (bytesRead == 0) {
                break;
            }

            sw.BaseStream.Write(buffer, 0, bytesRead);
            Console.WriteLine(bytesRead + " written.");
        }

        sw.Close();
    }

Client:

客户:

 StreamReader sr = new StreamReader("source.txt");

 TcpClient tcpClient = new TcpClient();
 tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.15"), 5442));

 byte[] buffer = new byte[1500];
 long bytesSent = 0;

 while (bytesSent < sr.BaseStream.Length) {
        int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
        tcpClient.GetStream().Write(buffer, 0, bytesRead);
        Console.WriteLine(bytesRead + " bytes sent.");

        bytesSent += bytesRead;
  }

  tcpClient.Close();

  Console.WriteLine("finished");
  Console.ReadLine();

回答by James Jones

More information about your connection needs is required in order to give you an appropriate solution. There are many protocols at your disposal and there are trade-offs for all of them. You will probably choose one of these two transport layers:

需要更多有关您的连接需求的信息才能为您提供合适的解决方案。有许多协议可供您使用,并且所有这些协议都需要权衡。您可能会选择以下两个传输层之一

UDP- This is a send-and-forget method of sending packets. Good for streaming media that doesn't necessarily have to be 100% correct.

UDP- 这是发送数据包的一种即发即忘的方法。适用于不一定必须 100% 正确的流媒体。

The good:

好的:

  1. No connection required.
  2. Very lightweight.
  1. 无需连接。
  2. 很轻。

The bad:

坏处:

  1. No guarantee of your packet reaching the destination (although most of the time they make it).
  2. Packets can arrive out of the order in which you sent them.
  3. No guarantee that their contents are the same as when you sent the packet.
  1. 无法保证您的数据包到达目的地(尽管大多数情况下它们都能到达)。
  2. 数据包的到达顺序可能与您发送它们的顺序不同。
  3. 不保证它们的内容与您发送数据包时的内容相同。

TCP- This is a connection-based protocol that guarantees predictable behavior.

TCP- 这是一种基于连接的协议,可保证可预测的行为。

The good:

好的:

  1. You will know for sure whether the packet has reached the destination or not.
  2. Packets will arrive in the order you sent them.
  3. You are guaranteed that 99.999999999% of the time your packets will arrive with their contents unaltered.
  4. Flow control - if the machine sending packets is sending too quickly, the receiving machine is able to throttle the sender's packet-sending rate.
  1. 您将确定数据包是否已到达目的地。
  2. 数据包将按照您发送的顺序到达。
  3. 您可以保证在 99.999999999% 的时间里,您的数据包到达时其内容不变。
  4. 流量控制 - 如果发送数据包的机器发送速度太快,接收机器能够限制发送者的数据包发送速率。

The bad:

坏处:

  1. Requires a connection to be established.
  2. Considerable more overhead than UDP.
  1. 需要建立连接。
  2. 开销比 UDP 多得多。

The list of pros and cons is by no means complete but it should be enough information to give you the ability to make an informed decision. If possible, you should take advantage of application layer-based protocols that already exist, such as HTTPif you are transferring ASCII text, FTPif you are transferring files, and so on.

利弊列表绝不是完整的,但它应该是足够的信息,使您能够做出明智的决定。如果可能,您应该利用已经存在的基于应用层的协议,例如HTTP(如果您正在传输 ASCII 文本)、FTP(如果您正在传输文件),等等。