C ++将客户端移出服务器循环并移至下一个功能

时间:2018-11-23 10:09:42

标签: c++ multithreading server-side

大家晚上好。 好的,我过去两天一直在搜索网络,但是没有找到任何解决方案。所以我决定最后在这里问一个。请原谅我,也许找不到我的解决方案的原因是因为我不知道如何正确表达它。我会在这里尽力而为。

我正在尝试让一个客户端连接到我的服务器,以便将其推入“登录”功能。在保持服务器处于其循环中的同时,等待新的连接到达,然后将它们转发到下一个功能。我唯一想到的就是多线程。我在我的客户端程序上使用它来打开一个窗口并保持与服务器的通信。这是我的代码:

这就是我设置标题的方式。我没有任何编译错误。程序进入我的传递函数时,只有一个例外。

#include "pch.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <sstream>

//////////////////////////SERVER MULTIPLE CLIENTS/////////////////////////
#pragma comment (lib, "ws2_32.lib")


///Function for transferring clients
void sockTransfer();

using namespace std;
class SERVER

这是我设置循环以保持接收连接的方式。在底部,您将看到我调出了我的函数,该函数用于发送客户端以尝试将其放置到单独的线程中。

    while (true)
    {
        //Copy the master port//?? What reason do you have to copy the port?
        fd_set copy = master;
        //Checks the ammount of connected clients(Open Sockets)

        int socketCount = select(0, &copy, nullptr, nullptr, nullptr);
        // While there is a connection to the server(Open Sockets) run this 
            loop
        for (int i = 0; i < socketCount; i++)
        {

            SOCKET sock = copy.fd_array[i];

            if (sock == listening)
            {
                //accept the new connection
                SOCKET client = accept(listening, nullptr, nullptr);

                cout << "Adding client socket to master Arrary...";

                //Add the new connection to the list of clients connected to 
                  //&master(array)
                FD_SET(client, &master);
                cout << "done" << endl;
                //Send a welcome message to the client
                send(client, bannarMsg.c_str(), bannarMsg.size() + 1, 0);
            cout << client << "has connected to socket: " << sock << endl;         


                ///////////////////////////////////TESTING/////////////////
                sockTransfer();

sockTransfer()标注发送到此处,尝试将其添加到新线程中。 所以我不得不分开功能,因为WinSock2.h和WS2tcpip.h标头与boost / asio.hpp标头冲突。

void sockTransfer()
{
clientMultithreading();
}

然后终于到达我的线程功能。在这里...

 void clientMultithreading()
    {
        thread tnew(login);
        if (1 == 0)
        {
            tnew.join();
        }

    }

我的希望是,一旦创建了新的套接字,它将回弹到侦听循环中的中断位置。

我知道这是一个非常糟糕的代码设置。几乎没有错误检查。一旦可以正常使用,我将对其进行清理和修改。

我知道这是一个冗长的问题。我试图删去这个问题不必要的代码。感谢您抽出宝贵的时间查看此内容。希望这个问题足够清楚。

0 个答案:

没有答案