Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7786211
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T20:22:48+00:00 2026-06-01T20:22:48+00:00

So I’m building a multithreaded socket library in windows and I’m getting the WSA

  • 0

So I’m building a multithreaded socket library in windows and I’m getting the WSA Not Started error when I call recv, even though I successfully get a client to connect to the server. I also had it working before I threaded it, but I don’t know what happened since then. Any help would be appreciated.

Spocket.hpp

    #include <iostream>
    #include <string>
    #include <Windows.h>
    #pragma comment (lib,"ws2_32.lib")

    static bool initialized_ = false;

    class Spocket
    {
    protected:
        WSADATA         wsaData_;
        SOCKET          hSocket_;
        sockaddr_in     service_;
        std::string     addr_;
        USHORT          port_;
        int             exitCode_;

    public:
        Spocket() { 
            initialize(); 
            create_socket(); 
        }
        Spocket(std::string addr, USHORT port)
            : addr_( addr ), port_( port ) { 
                initialize(); 
                create_socket(); 
        }
        Spocket(Spocket spock, SOCKET sock)
            : hSocket_( sock ), 
            wsaData_( spock.wsaData_ ),
            service_( spock.service_ ),
            addr_( spock.addr_ ),
            port_( spock.port_ ) 
        { 
            initialize(); 
        }
        virtual ~Spocket() { close(); }

        void initialize();
        void create_socket();
        void close();

        template<typename T>
        int recv_data(T* i) {
            int ret = recv( hSocket_, reinterpret_cast<char*>(i), 32, 0 );
            if( ret == SOCKET_ERROR )
                cerr << WSAGetLastError() << endl;
            return ret;
        }

        template<typename T>
        int send_data(T* i) {
            int ret = send( hSocket_, reinterpret_cast<char*>(i), sizeof(i), 0 );
            if( ret == SOCKET_ERROR )
                cerr << WSAGetLastError() << endl;
            return ret;
        }
    };

class ServerSpocket : public Spocket
{
public:
    ServerSpocket(std::string addr, USHORT port);
    Spocket* accept_clients();
};


class ClientSpocket : public Spocket
{
public:
    ClientSpocket(std::string addr, USHORT port);
};

Spocket.cpp

#include <iostream>
using namespace std;
#include "../include/spocket.hpp"

void Spocket::initialize() {
    if(!initialized_)
    {
        cout << "Initializing socket..." << endl;

        exitCode_ = EXIT_SUCCESS;
        int iResult = WSAStartup( MAKEWORD(2,2), &wsaData_ );
        if( iResult != NO_ERROR ) {
            cerr << "WSAStartup failed" << endl;
            exitCode_ = EXIT_FAILURE;
            close();
        }
        initialized_ = true;
    }
}

void Spocket::create_socket() {
    hSocket_ = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if( hSocket_ == INVALID_SOCKET )
    {
        cerr << "Error at socket(): " << WSAGetLastError() << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }

    service_.sin_family = AF_INET;
    service_.sin_addr.s_addr = inet_addr(addr_.c_str());
    service_.sin_port = htons(port_);
}

void Spocket::close() {
    closesocket( hSocket_ );
    WSACleanup();
}

ServerSpocket::ServerSpocket(std::string addr, USHORT port) : Spocket(addr, port) {
    if( bind( hSocket_, (SOCKADDR*)&service_, sizeof(service_) ) == SOCKET_ERROR )
    {
        cerr << "Failed to bind" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }

    if( listen( hSocket_, 1 ) == SOCKET_ERROR )
    {
        cerr << "Error listening on socket" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }
}

Spocket* ServerSpocket::accept_clients() {
    cout << "Waiting for connection...\n";
    SOCKET hAccepted = INVALID_SOCKET;
    while( hAccepted == INVALID_SOCKET )
        hAccepted = accept( hSocket_, NULL, NULL );
    return new Spocket( *this, hAccepted );
}

ClientSpocket::ClientSpocket(std::string addr, USHORT port) : Spocket(addr, port) {
    if( connect( hSocket_, (SOCKADDR*)&service_, sizeof(service_) ) == SOCKET_ERROR )
    {
        cerr << "Failed to connect" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }
}

Server_main.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <spocket.hpp>
using namespace std;

vector<HANDLE> hThreads;
vector<DWORD> dwThreadIds;

struct ConnectionInfo
{
    string ip;
    unsigned int port;
    ConnectionInfo( string ip_, unsigned int port_ ) : ip(ip_), port(port_){}
};
static ConnectionInfo ci( "127.0.0.1", 27015 );

DWORD WINAPI clientSession( LPVOID lpParam )
{
    // create new socket to listen for connection attempts
    ConnectionInfo arg = *reinterpret_cast<ConnectionInfo*>(lpParam);
    ServerSpocket listenSock( arg.ip, arg.port );

    // spawn a duplicate thread when a connection is made, and close the current listening socket
    Spocket* sessionSock = listenSock.accept_clients();
    listenSock.close();
    cout << "client connected..." << endl;
    /*
    hThreads.push_back( CreateThread( NULL, 0, clientSession, &ci, 0, NULL ) );
    */

    // service the connected client
    string msg;
    while( sessionSock->recv_data(&msg) != SOCKET_ERROR && msg != "goodbye!" )
    {
        cout << msg << endl;
        msg.clear();
    }

    cout << "finished with client..." << endl;

    // wait quietly for server shutdown
    while( true )
        Sleep( 200 );
    return 0;
}

int main() {
    cout << "[Server]" << endl;
    cout << "starting up..." << endl;

    hThreads.push_back( CreateThread( NULL, 0, clientSession, &ci, 0, NULL ) );

    string input = "";
    do 
        cin >> input;
    while( input != "exit" );

    // close all thread handles here
    cout << "shutting down..." << endl;
    return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T20:22:48+00:00Added an answer on June 1, 2026 at 8:22 pm

    I beleive you must keep the “original” socket alive. Move listenSock.close(); after the sessionSock->recv_data() loop.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.