socket program error:Socket operation on non-socket

这个错误表示你的socket 操作有问题。

第一步:如何定位错误出现的地方

但不是说一定就是返回错误信息的那个函数。举个例子来说:connect: Socket operation on non-socket 这句话表示我的错误出现在connect函数,但是事实并不是这个样子,前面调用的有关socket的函数都是有可能出错的。这里是一个客户端返回的错误,前面可能出错的函数主要是 socket()函数。

如果你是服务器端出现的这个错误,那么可能出现错误的地方就多了如socket()、bind()、listen()等。

第二步:分析出现这个错误的原因及解决方法

综合网上的一些帖子和相关的一些blog。这个错误的真凶大部分是由没有添加()引起的,也就是在调用函数的时候出现了优先级的错误。可以参看下面的示例:

出错的代码:

if( sockfd=socket(AF_INET,SOCK_STREAM,0)==-1)

正确的代码是:

if(   (   sockfd=socket(AF_INET,SOCK_STREAM,0)  )==-1)


上面只是提供一个示例,你的这个错误可能出现在socket的其他函数中,同样会出现上面的错误提示。


后记:你还可以将上面的一句话拆成两句话,这样就不容易出错了。


### SocketTask in C# .NET Framework #### Implementation and Usage Examples In the context of asynchronous operations within the .NET framework, `SocketTask` represents a specialized task that wraps around socket-based network communications. The primary purpose is to facilitate non-blocking communication over networks using sockets without freezing or blocking the main thread of execution. For applications requiring high responsiveness alongside efficient resource utilization during network interactions, leveraging tasks specifically designed for handling IO-bound workloads becomes essential[^2]. Below demonstrates how one can implement and utilize `SocketTaskExtensions.ConnectAsync`, which returns a Task object representing an ongoing connect operation: ```csharp using System; using System.Net.Sockets; using System.Threading.Tasks; public class NetworkClient { private readonly string _hostNameOrAddress; private readonly int _portNumber; public NetworkClient(string hostNameOrAddress, int portNumber){ _hostNameOrAddress = hostNameOrAddress; _portNumber = portNumber; } public async Task ConnectToServer(){ var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try{ await socket.ConnectAsync(_hostNameOrAddress, _portNumber).ConfigureAwait(false); Console.WriteLine("Connected successfully."); // Proceed with sending/receiving data... } catch(Exception ex){ Console.Error.WriteLine($"Failed to establish connection: {ex.Message}"); } finally { socket.Dispose(); } } } ``` The above example showcases connecting asynchronously to a server via TCP protocol utilizing `ConnectAsync`. This method ensures that while waiting for the remote endpoint acknowledgment, other parts of the program continue executing normally instead of being stalled until completion occurs[^1]. Additionally, when dealing with concurrent connections or processing large amounts of incoming/outgoing packets simultaneously, it’s crucial to manage resources effectively through proper synchronization mechanisms provided by the runtime environment as well as applying best practices from literature on parallel programming concepts[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值