简体   繁体   English

C ++在SOCKET上失败的accept()方法

[英]C++ Failing at SOCKET accept() Method

I am currently make a Server, I learned to make something like this: 我目前正在制作服务器,我学会了这样做:

while(true)
{
     SOCKET s = accept(s, ....)

     // do something with the connection
     printf("connection\n");
}

I learned that it will stuck at accept(..) while there isnt a connection. 我知道它会在没有连接的情况下陷入接受(..)。 In my Program there isnt any connection yet, but it get overflowed with connection ?? 在我的程序中还没有任何连接,但它连接溢出? I mean my Console got spammed with "connection". 我的意思是我的控制台被“连接”垃圾邮件。

So whats wrong? 那么什么是错的?


THX Guys i fixed it now :) THX伙计们,我现在修复了它:)

Most likely it returns immediately with an error which you don't seem to be checking. 很可能它会立即返回一个您似乎没有检查的错误。 Eg it may be that s wasn't properly created, etc. 例如,可能是未正确创建s等。

Edit : just noticed that you are assigning the result of accept() to the same 's', which is terribly wrong. 编辑 :刚刚注意到你将accept()的结果分配给同一个's',这是非常错误的。 Your 's' is a general listening socket presumably created by socket(), bound by bind() and set to listening by listen(), whereas the return value of accept() is another socket which you should use for transfering data. 你的's'是一个普通的监听套接字,可能由socket()创建,由bind()绑定并设置为listen()监听,而accept()的返回值是另一个套接字,你应该用它来传输数据。

Take a look at this for example (just found by Googling): http://www.cs.odu.edu/~cs476/fall03/lectures/sockets.htm 看一下这个例子(Googling找到): http//www.cs.odu.edu/~cs476/fall03/lectures/sockets.htm

我调试了一下,我得到的每个失败套接字都有值:4294967295。

I added some checks: 我添加了一些检查:

while(true)
{
    SOCKET s = 
        accept(m_Socket, (sockaddr*)&from, &fromlen);

    if(s != SOCKET_ERROR)
    {
        printf("Client connected to the Server. ");
        Client* client = new Client(s); // Memory Leak here .. i know
    }
}

My CPU is at 16%, although there isnt any Client connected. 我的CPU是16%,虽然没有连接任何客户端。

Call WSAGetLastError() and see what it returns. 调用WSAGetLastError()并查看它返回的内容。 This error code can then be input into the Error Lookup tool (you'll find it in the tools menu of Visual Studio). 然后可以将此错误代码输入到错误查找工具中(您可以在Visual Studio的工具菜单中找到它)。 You have most likely initialized your server socket incorrectly. 您很可能错误地初始化了服务器套接字。

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

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