• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Vorel512

Sharing a socket between processes VC++

10 posts in this topic

Hi,

My problem is, that I have created an MFC DLL which handles the network side of my program.
Everything goes well except one thing...
The parent/main process can switch between server/client modes like: server,client, server and client (like WarCraft3).
When I want to run two or more "server and client" instance of the program, the first goes fine, but the others come back with error messages.
Also I have set up IPC so they can communicate. The first gets the process id, and calls WSADuplicateSocket(), and the caller calls WSASocket().
All of them return 0 as error message, so as far as I know, they works fine, but the recvfrom command returns with error message 10038 WSAENOTSOCK.
Ohh I almost forgot... The binding fails in the processes except in the first. While the first process should call bind, not the others, I think that is not the problem.

My code:
[code]#define PIPE_SIZE sizeof(WSAPROTOCOL_INFO)
WSAPROTOCOL_INFO protocolinf;
.
.
.
If the process can create the pipe
.
.
WSADuplicateSocket(serverSocket,outBytes,&protocolinf);
.
.
If not...
.
.
serverSocket = WSASocket(protocolinf.iAddressFamily, protocolinf.iSocketType, protocolinf.iProtocol, &protocolinf, 0, NULL);
.
.
.[/code]

Every help is appreciated!
0

Share this post


Link to post
Share on other sites
Why are you duplicating the socket?
Either you're using UDP, in which case you can keep using the same socket all the time.
Or you're using TCP, in which case you will use one socket per peer you are connected to.
In neither case do you need to ever duplicate a socket.
There are probably some assumptions in your code that you are not spelling out, and that we need to understand in order to help.
0

Share this post


Link to post
Share on other sites
OK, so my corresponding code (UDP):

I have a class for the network stuff, it contains:
(.h)
[code]
class asd_API asd {
public:
asd(){};
~asd(){};
void Connect(char *toIP);
void ConnectUDP(char *toIP);
private:
static int InitializeUDP();
static void UDPResponseThread();
static int UDPStartSocket();
static int UDPStartServerListening(int serverSocket2);
static void UDPReceiveThread();
static void EndServer(int socket);
static void DulpicateSocket();
};
[/code]

(.cpp)
[code]
#define g_szPipeName "\\\\.\\Pipe\\CSEPPPipe"
#define PIPE_SIZE sizeof(WSAPROTOCOL_INFO)
#define MAX_MESSAGE_SIZE 100
int nBytes;
char buffer[MAX_MESSAGE_SIZE];
char myID[MAX_MESSAGE_SIZE-3] = "id=none";
u_long iMode=1; //1 -non-blocking
int p_int;
int n_Type;
int serverSocket;
int clientSocket;
int thread;
char *n_IP = "127.0.0.1";
unsigned short n_Port = 7700;
bool n_RunThread = true;
bool n_Protocol = 0;
HANDLE AcceptOrReceiveThread;
HANDLE ResponseThread;
HANDLE DuplicateThread;
HANDLE IdentThread;
HANDLE Hmutex;
HANDLE Imutex;
struct sockaddr_in server;
struct sockaddr_in si_other;
struct hostent *hostEntity;
int silen=sizeof(si_other);
[/code]

[code]

int asd::InitializeUDP()
{
serverSocket = UDPStartSocket();
DuplicateThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DulpicateSocket, NULL, 0, NULL);

if (DuplicateThread == NULL)
{
EndServer(serverSocket);
return 1;
}
SetThreadPriority(AcceptOrReceiveThread,THREAD_PRIORITY_BELOW_NORMAL);
if (serverSocket == -1)
{
return 1;
}
Hmutex = CreateMutex(NULL, false, NULL);// Create the mutex
if (Hmutex == NULL)
{
EndServer(serverSocket);
return 1;
}
Imutex = CreateMutex(NULL, false, NULL);// Create the mutex
if (Imutex == NULL)
{
EndServer(serverSocket);
return 1;
}
ResponseThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)UDPResponseThread, NULL, 0, NULL);

if (ResponseThread == NULL)
{
EndServer(serverSocket);
return 1;
}
SetThreadPriority(ResponseThread,THREAD_PRIORITY_BELOW_NORMAL);
AcceptOrReceiveThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)UDPReceiveThread, NULL, 0,NULL);

if (AcceptOrReceiveThread == NULL)
{
EndServer(serverSocket);
return 1;
}
SetThreadPriority(AcceptOrReceiveThread,THREAD_PRIORITY_BELOW_NORMAL);

Sleep(100);// Let the threads start up;
return 0;
}
[/code]

[code]
int asd::UDPStartSocket()
{
int error;
WSAData wsaData;
if ((error = WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR)
{
return -1;
}
int mySocket;
mySocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (mySocket == SOCKET_ERROR)
{
return -1;
}
switch (n_Type)
{
case 0:
UDPStartServerListening(mySocket);
break;
default:
ioctlsocket(mySocket,FIONBIO,&iMode); // in UDPStartServerListening also.
break;
}
return mySocket;
}
[/code]

[code]
int asd::UDPStartServerListening(int serverSocket2)
{
server.sin_family = AF_INET;
server.sin_port = htons(n_Port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(serverSocket2, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
int error = WSAGetLastError();

if (error == 10048) //already in use
{
DulpicateSocket();
}
else
{
closesocket(serverSocket2);
return -1;
}
}
else
ioctlsocket(serverSocket2,FIONBIO,&iMode);
return 0;
}
[/code]

[code]
void asd::DulpicateSocket()
{
switch (n_Type)
{
case 0:
HANDLE hPipe;

hPipe = CreateNamedPipe(
g_szPipeName, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
PIPE_SIZE, // output buffer size
PIPE_SIZE, // input buffer size
NMPWAIT_USE_DEFAULT_WAIT, // client time-out
NULL); // default security attribute
if (INVALID_HANDLE_VALUE == hPipe)
{
_tprintf( TEXT("Could not create pipe. GLE=%d\n"), GetLastError() );
}
if (GetLastError() == 183)
{
hPipe = CreateFile(
g_szPipeName, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
char szBuffer[10];
DWORD cbBytes;
sprintf(szBuffer, "%d", GetCurrentProcessId());
WriteFile(
hPipe,
szBuffer,
sizeof(szBuffer),
&cbBytes,
NULL
);
bool van = 1;
for(;;)
{
van = ReadFile(
hPipe, // pipe handle
&protocolinf, // buffer to receive reply
sizeof(WSAPROTOCOL_INFO), // size of buffer
&cbBytes, // number of bytes read
NULL); // not overlapped
if(van == 0)
break;
Sleep(1);
}

serverSocket = WSASocket(protocolinf.iAddressFamily, protocolinf.iSocketType, protocolinf.iProtocol, &protocolinf, 0, NULL);
}
else
{
for(;;) // for multiple instances
{
ConnectNamedPipe(hPipe,NULL); //wait for client to connect to pipe
char szBuffer[10];
DWORD cbBytes;
DWORD rBytes;
ReadFile(
hPipe, // pipe handle
szBuffer, // buffer to receive reply
sizeof(szBuffer), // size of buffer
&cbBytes, // number of bytes read
NULL); // not overlapped
DWORD outBytes = atoi(szBuffer);
WSADuplicateSocket(serverSocket,outBytes,&protocolinf);
WriteFile(
hPipe,
&protocolinf,
sizeof(WSAPROTOCOL_INFO),
&cbBytes,
NULL
);
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
Sleep(1);
}
CloseHandle(hPipe);
}
break;//switch
default:
break;
}//switch
}
[/code]

[code]
void asd::UDPReceiveThread()
{
bool exists = false;
for (;;)
{
WaitForSingleObject(Hmutex, INFINITE); // Lock the mutex for UDPTalking
nBytes = recvfrom(serverSocket, buffer, MAX_MESSAGE_SIZE, 0, (SOCKADDR *)&si_other, (int *) &silen); // error 10038 when an instace of this already running.
if (nBytes == SOCKET_ERROR)
{

int error = WSAGetLastError();
if (error == 10057 || error == 10054 || error == 10014)
{
}
else if (error == 10035)
{
}
else
{
std::cout<< "----------------------->" << error << "\n";
Sleep(1000);// only for testing
}

}
else
{
...
}
buffer[0] = '\0';
ReleaseMutex(Hmutex);
Sleep(1);
}
UDPClients.RemoveAll();
}
[/code]

[attachment=6609:Untitled.png]
0

Share this post


Link to post
Share on other sites
That still doesn't explain [b]why[/b] you are trying to duplicate the socket. It isn't clear, for example, what your processes are going to do with this shared socket?

Can you give a high level description of your goal?
0

Share this post


Link to post
Share on other sites
I don't believe your approach will work. WSADuplicateSocket is intended for socket handoff, not socket sharing:
[quote]
The descriptors that reference a shared socket can be used independently for I/O. However, the Windows Sockets interface does not implement any type of access control, so it is up to the processes involved to coordinate their operations on a shared socket. Shared sockets are typically used to having one process that is responsible for creating sockets and establishing connections, and other processes that are responsible for information exchange.
[/quote]
Maybe this is what you want to do?

If not, a simple solution to the original problem to that is to to have the secondary servers connect to the primary one, and have the primary one demultiplex the data as it comes in (however you propose to handle that) and copy it to the correct "local" connection to the secondary server.

One approach might be for the secondary server to connect to the problematic socket, and identify itself as a server somehow. The primary server would echo data back out that socket when it is intended for this sub-server. Another might use a local IPC mechanism, like a named pipe, to connect to the primary server, not unlike what you were trying to do with the socket description, but with the actual data instead.

That said, this is still highly unusual. Multiplexing connections like that is generally handled at a different level (e.g. a SSH tunnel), if it is indeed necessary at all.
1

Share this post


Link to post
Share on other sites
I will think about SSH tunneling.
If for example server 1 shut down, server 2 should gain control above the socket, therefore IPC and any relations falls out.

Thank you for your reply, it helped me a LOT!!!!!!
0

Share this post


Link to post
Share on other sites
Are you trying to implement a load balancer? Failover?

Having one server take over a socket doesn't make much sense. To be able to actually serve meaningful data, second server would need to have bit-exact copy of old server's state. So there would need to be two servers running at same time, performing exactly the same actions, including some that might be difficult to duplicate due to state being held by kernel.

While attempts at such systems have been made, native applications simply aren't capable of getting it right, there's too many factors outside of process' control. Java attempted to provide that through Serializable mechanism and one of most isolated VMs, but they gave up due to too many unsolvable issues.
0

Share this post


Link to post
Share on other sites
[indent=1][color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif][size=4][left]I would like to run multiple servers on the same UDP/TCP socket. So users can "dualbox". [/left][/size][/font][/color][/indent]

[color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif][size=4][left]Duplicating the socket won't do that, even if you were to manage to make it work. (It is possible to share a socket between processes in Linux, using for example fork() -- that sharing would have the same problem)[/left][/size][/font][/color]
Once the socket is duplicated, and a single packet comes in, only one of the two processes that use the socket will get the packet. Which of the two processes gets it is pretty much random. When you run two servers, you want messages from clients of server A to go to server process A, and messages from clients of server B to go to server process B. The only way to arrange this is to use two different sockets, each bound to a different port -- that's the only way the OS is going to know where to send which incoming packets.

Also, there is no such things as a UDP/TCP socket. UDP sockets and TCP sockets work differently at the IP and OS level, and you need to design appropriately for each.
0

Share this post


Link to post
Share on other sites
[quote name='Vorel512' timestamp='1325604021' post='4899264']
If for example server 1 shut down, server 2 should gain control above the socket, therefore IPC and any relations falls out.
[/quote]

There are better solutions for taking over service on a port. Most commonly, you'll use something like HAProxy to serve requests on the port, and then configure HAProxy to forward the requests to some other process. If you grow in scale larger than what a single HAProxy machine can deal with, you can buy hardware load balancers that can do the same thing for a few million connections at a time :-)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0