Hi,
I've juggled this previously-working code around a bit to get it working for my implementation but now recv is returning -1 and is crashing my program.
You'll probably be able to spot the issue straight away but I've been staring at this screen for hours and I just cannot figure it out.
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <winsock.h>
#include <vector>
#include "Player.h"
#pragma comment(lib, "Ws2_32.lib")
std::vector<Player> players;
int main()
{
printf("Server started\r\n");
SOCKET connection_socket;
WSADATA wsaData;
sockaddr_in server;
int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (ret != 0) return 0;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(123);
connection_socket = socket(AF_INET, SOCK_STREAM, 0);
if (connection_socket == INVALID_SOCKET) return 0;
if (bind(connection_socket, (sockaddr*)&server, sizeof(server)) != 0) return 0;
if (listen(connection_socket, 5) != 0) return 0;
SOCKET client;
sockaddr_in from;
int fromlen = sizeof(from);
while (true)
{
client = accept(connection_socket, (struct sockaddr*)&from, &fromlen);
printf("Client connected\r\n");
Player p;
PlayerConnection* connection = new PlayerConnection();
connection->init(client);
p.init(connection);
players.push_back(p);
}
closesocket(connection_socket);
WSACleanup();
return 0;
}
#include "stdafx.h"
#include "PlayerConnection.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <winsock.h>
#include <vector>
#include <iostream>
struct ThreadData
{
PlayerConnection* instance;
SOCKET& socket;
};
DWORD WINAPI ThreadProcedure(LPVOID lpParam)
{
ThreadData* data = (ThreadData*)lpParam;
PlayerConnection* instance = data->instance;
SOCKET socket = data->socket;
char buf[100];
int res;
while (true)
{
res = recv(socket, buf, sizeof(buf), 0);
Sleep(10);
printf("res: %i\n", res);
if (res <= 0)
{
printf("EXITING THREAD");
closesocket(socket);
ExitThread(0);
}
if (strstr(buf, "exit"))
{
instance->disconnect();
}
else
{
printf("Client said: %s\n", buf);
Sleep(10);
char txbuf[100];
strcpy_s(txbuf, "You said: ");
strcat_s(txbuf, buf);
instance->send_message(txbuf);
}
strcpy_s(buf, "");
}
return 0;
}
void PlayerConnection::init(SOCKET& socket)
{
this->socket = socket;
ThreadData td = { this, socket };
HANDLE threadHandle = CreateThread(NULL, 0, ThreadProcedure, &td, 0, NULL);
}
void PlayerConnection::send_message(char* buf)
{
send(socket, buf, strlen(buf), 0);
}
void PlayerConnection::disconnect()
{
closesocket(socket);
ExitThread(0);
}
What I have tried:
I was thinking it might be an issue to do with either accessing objects created on the main thread from this new thread, but even if I directly pass the socket to the method, it doesn't even work using that.