套接字没有阻塞现有的循环 [英] Socket without blocking existing loop

查看:64
本文介绍了套接字没有阻塞现有的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作为无限循环运行的应用程序。我正在尝试通过网络在此应用程序和另一个应用程序之间发送和接收消息。我一直在看异步套接字示例  https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example
但我不太明白。我想知道这是否是最好的approuch或我是否应该看其他东西?

I have an application that is running as an infinite loop. I'm trying to be able to send and receive messages between this application and another application over network. I'v been looking at Async socket example https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example but I dont quite understand it. Im wondering if this is the best approuch or if I should be looking at something else?

问候

推荐答案

该代码演示了如何使用套接字进行异步调用,因此这是一个很好的例子。如果您不想阻止,则只需要修改它们提供的StartListening方法。它们有一个循环,因此:a)它将允许任何#连接
和b)因此控制台应用程序不会终止。调整逻辑以满足您的需求,你很好。在线发布了很多很多关于如何在.NET中使用Socket的例子。

That code is demoing how to make async calls with a socket so it is a fine example. If you don't want to block then you would just need to modify the StartListening method that they provided. They have a loop so that: a) it will allow any # of connections and b) so the console app won't terminate. Adjust that logic to fit your needs and you're fine. There are also many, many other examples posted online on how to use Socket in .NET.

我建议你看一下
TcpListener / TcpClient
。除非您对套接字编程感到满意,否则这两种类型的设计旨在包装套接字并使其更易于使用。他们没有任何缺点,如果您直接使用套接字,他们会处理一些常见的事情,你可以用
编写代码。对于TcpListener,您使用-Async方法来处理任务而不是BeginAccept,但是它们的工作方式类似。这是一个较旧的

文章
如何在异步情况下使用它。还有其他方法。

I would recommend that you take a look at TcpListener/TcpClient instead though. Unless you are comfortable with socket programming these 2 types are designed to wrap a socket and make it easier to use them. There isn't any disadvantages to them and they handle some common things that you'd have to write code for if you used the socket directly. For TcpListener you'd use the -Async methods to work with tasks instead of BeginAccept but otherwise they work similar. Here's an older article on how you might use it in an async situation. There are other approaches as well.


这篇关于套接字没有阻塞现有的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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