Skip to main content
gamedev.net
🔒 Locked

using enet

Started by supagu Aug 9, 2006 at 5:47 AM 6 replies 4k views
Original Post
supagu
supagu
i've decided to try out enet for my networking in a game im making. Now i have 2 questions or problems. 1. i cant seem to connect to the server i'm pretty much following the tutorials from here: http://enet.cubik.org/Tutorial.html ive got the server running in an infinite loop checking for connections:

while (1)
	{
		/* Wait up to 1000 milliseconds for an event. */
		while (enet_host_service (stream.GetENetHost(), & event, 0) > 0)
		{
// code here is exactly the same as in "Managing an ENet host" in the tut
}
}
client simply creates a host and attempts to connects as per the sample. The server and client are both running on the same machine for testing, the server listens on any nic on port 1234 as in the tut, while client connects to my IP with 1234 as the port. 2. does enet have some sort of ping measuring ability? i've seen reference to ping in the source code edit: okay solved number 2 - enet_peer_ping (ENetPeer *)
supagu
supagu
do to lack of responses i assume this is due to lack of info, so i'll post my source code:

namespace ENet{	int	Init()			{ 		return enet_initialize(); 	}	void Deinit()		{ 		enet_deinitialize(); 	}};ENetStream::ENetStream() :	mHost(0),	mPeer(0){}bool ENetStream::Listen(int port){	ENetAddress address;    /* Bind the server to the default localhost.     */    /* A specific host address can be specified by   */    /* enet_address_set_host (& address, "x.x.x.x"); */    address.host = ENET_HOST_ANY;    address.port = port;    mHost = enet_host_create (& address /* the address to bind the server host to */,                                  32      /* allow up to 32 clients and/or outgoing connections */,                                  0      /* assume any amount of incoming bandwidth */,                                  0      /* assume any amount of outgoing bandwidth */);	return mHost != 0;}bool ENetStream::Connect(const char* server, int port){    mHost = enet_host_create (NULL /* create a client host */,                1 /* only allow 1 outgoing connection */,                57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,                14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);    if (mHost == NULL)		return false;	ENetAddress address;    ENetEvent event;    /* Connect to some.server.net:1234. */    enet_address_set_host (& address, server);    address.port = port;    /* Initiate the connection, allocating the two channels 0 and 1. */    mPeer = enet_host_connect (mHost, & address, 2);            if (mPeer == NULL)		return false;    /* Wait up to 5 seconds for the connection attempt to succeed. */    if (enet_host_service (mHost, & event, 5000) > 0 &&        event.type == ENET_EVENT_TYPE_CONNECT)    {        return true;    }    /* Either the 5 seconds are up or a disconnect event was */    /* received. Reset the peer in the event the 5 seconds   */    /* had run out without any significant event.            */    enet_peer_reset (mPeer);	return false;}void ENetStream::Disconnect(){	enet_host_destroy(mHost);	mHost = 0;}bool ENetStream::Send(Packet* packet, int channel){	return enet_peer_send(mPeer, channel, packet->mPacket) == 0;}void ENetStream::Receive(Packet* packet){}void Server(){	ENetStream stream;	bool connect = stream.Listen(1234);	ENetEvent event;    	while (1)	{		/* Wait up to 1000 milliseconds for an event. */		while (enet_host_service (stream.GetENetHost(), & event, 1000) > 0)		{			switch (event.type)			{			case ENET_EVENT_TYPE_CONNECT:				printf ("A new client connected from %x:%u.\n", 						event.peer -> address.host,						event.peer -> address.port);				/* Store any relevant client information here. */				event.peer -> data = "Client information";				break;			case ENET_EVENT_TYPE_RECEIVE:				printf ("A packet of length %u containing %s was received from %s on channel %u.\n",						event.packet -> dataLength,						event.packet -> data,						event.peer -> data,						event.channelID);				/* Clean up the packet now that we're done using it. */				enet_packet_destroy (event.packet);	            				break;	           			case ENET_EVENT_TYPE_DISCONNECT:				printf ("%s disconected.\n", event.peer -> data);				/* Reset the peer's client information. */				event.peer -> data = NULL;			}		}	}}void Client(){	ENetStream stream;	bool connect = stream.Connect("192.168.0.60", 1234);	if (connect)		printf ("Connection successful.\n");}int main(int argc, const char* args[]){	if (ENet::Init())    {        fprintf (stderr, "An error occurred while initializing ENet.\n");        return EXIT_FAILURE;    }	if (argc >= 2 && strcmpi(args[1], "server") == 0)		Server();	else		Client();	ENet::Deinit();	return 0;}
doctorsixstring
doctorsixstring
I was looking at the ENet site a few days ago, and it seemed pretty nice, but I wasn't sure if many people actually used it. I was also in the process of learning RakNet (still am), which has a lot more features. Of course, it also costs a small amount of money.

I'm going to take a look at the tutorials, and I'll let you know if I figure out an answer to your problem.

- Mike
doctorsixstring
doctorsixstring
Okay, I went through the tutorial and was able to get a client to connect to a server. Its not that pretty (C++ hasn't been my primary language for a few years), but it works.

I tried running your code, but you didn't post your header file. I tried to guess at the ENetStream class, but some code is missing. Could you post the header and source definitions for the Packet class, and any missing methods from ENetStream (like GetENetHost)? I'd like to execute your code and see if I find anything wrong. It looks fine to my naked eye.

Here is my code, if you're curious:
#include "enet/enet.h"#include "enet/win32.h"#include <cstdio>const char HOST[] = "192.168.123.100";void waitForPackets(ENetHost* host){	ENetEvent event;        // Wait up to 1000 milliseconds for an event.	printf("Waiting for event...\n");    while (enet_host_service (host, & event, 1000) > 0)    {		printf("Received event...(type:%i, channel:%i, host:%i, port:%i)\n",			event.type,			event.channelID,			event.peer->address.host,			event.peer->address.port);		switch (event.type)        {        case ENET_EVENT_TYPE_CONNECT:            printf ("A new client connected from %x:%u.\n",                     event.peer -> address.host,                    event.peer -> address.port);            // Store any relevant client information here.            event.peer -> data = "Client information";            break;        case ENET_EVENT_TYPE_RECEIVE:            printf ("A packet of length %u containing %s was received from %s on channel %u.\n",                    event.packet -> dataLength,                    event.packet -> data,                    event.peer -> data,                    event.channelID);            // Clean up the packet now that we're done using it.            enet_packet_destroy (event.packet);                        break;                   case ENET_EVENT_TYPE_DISCONNECT:            printf ("%s disconected.\n", event.peer -> data);            // Reset the peer's client information.            event.peer -> data = NULL;        }	}}void server(){		ENetAddress address;    ENetHost * server;    // Bind the server to the default localhost.     // A specific host address can be specified by      // enet_address_set_host (& address, "x.x.x.x");    address.host = ENET_HOST_ANY;    address.port = 1234;    server = enet_host_create (& address, // the address to bind the server host to                                 32,      // allow up to 32 clients and/or outgoing connections                                  0,      // assume any amount of incoming bandwidth                                  0 );     // assume any amount of outgoing bandwidth    if (server == NULL)    {        fprintf (stderr,                  "An error occurred while trying to create an ENet server host.\n");        exit (EXIT_FAILURE);    }    printf("Server started...\n");	while(true)		waitForPackets(server);    enet_host_destroy(server);}void client(){	ENetHost* client = enet_host_create (NULL, // create a client host                1, // only allow 1 outgoing connection                57600 / 8, // 56K modem with 56 Kbps downstream bandwidth                14400 / 8 );// 56K modem with 14 Kbps upstream bandwidth		if (client == NULL)    {        fprintf (stderr,                  "An error occurred while trying to create an ENet client host.\n");        exit (EXIT_FAILURE);    }    printf("Client started...\n");	ENetAddress address;    ENetEvent event;    ENetPeer *peer;    // Connect to some.server.net:1234.    enet_address_set_host(&address, HOST);    address.port = 1234;    // Initiate the connection, allocating the two channels 0 and 1.    peer = enet_host_connect(client, &address, 2);            if (peer == NULL)    {       fprintf (stderr, "No available peers for initiating an ENet connection.\n");       exit (EXIT_FAILURE);    }        // Wait up to 5 seconds for the connection attempt to succeed.    if (enet_host_service (client, & event, 5000) > 0 &&        event.type == ENET_EVENT_TYPE_CONNECT)    {        printf ("Connection to %s:%i succeeded.", HOST, address.port);    }    else    {        // Either the 5 seconds are up or a disconnect event was        // received. Reset the peer in the event the 5 seconds          // had run out without any significant event.                   enet_peer_reset (peer);        printf ("Connection to %s:%i failed.", HOST, address.port);    }	while(true)		waitForPackets(client);    enet_host_destroy(client);}int main (int argc, char ** argv) {    if (enet_initialize () != 0)    {        fprintf (stderr, "An error occurred while initializing ENet.\n");        return EXIT_FAILURE;    }	char str[512];	printf("(C)lient or (S)erver?\n");	gets(str);	if (str[0]=='c' || str[0]=='C')	{		client();	}	else	{		server();	}    atexit (enet_deinitialize);}


Server Output
(C)lient or (S)erver?
s
Server started...
Waiting for event...
Waiting for event...
Received event...(type:1, channel:204, host:1685825728, port:1741)
A new client connected from 647ba8c0:1741.
Waiting for event...
Waiting for event...
Waiting for event...

Client Output
(C)lient or (S)erver?
c
Client started...
Connection to 192.168.123.100:1234 succeeded.Waiting for event...
Waiting for event...
Waiting for event...
supagu
supagu
ah lol stupid me, i copied your example, then realized my ip was 1.60 not 0.60
so now its all working except i can only send packets from the client to the server, when i attempt to send a packet from the server to the client it errors saying

"Error sending outgoing packets: No Error"

and my client never recevies anything

[Edited by - supagu on August 12, 2006 7:40:30 AM]
Ranger_One
Ranger_One
Are you using your EnetStream class above? I don't see any linking (to actual use) for mPeer, and that is what determines where a packet is sent with send(). Just a thought. Show us the source!
supagu
supagu
okay here is my complete source:

#ifndef _ENETSTREAM_H_#define _ENETSTREAM_H_#include "ENet/ENet.h"#include "Packet.h"namespace ENet{	int		Init();	void	Deinit();};enum NetStreamEventType{	NET_None,	NET_Connect,	NET_Disconnect,	NET_ReceivePacket,};struct NetStreamEvent {	NetStreamEventType	type;	Packet				packet;	ENetPeer*			peer;};class ENetStream{public:	ENetStream();	bool			Listen(int port);	bool			Connect(const char* server, int port);	void			Disconnect();	ENetHost*		GetENetHost()								{ return mHost; }	unsigned int	GetPingTime()								{ return mPeer ? mPeer->roundTripTime : 0; }	bool			Send(Packet* packet);	bool			Receive(Packet* packet);	bool			GetEvent(NetStreamEvent& event);	void			ReleaseEvent(NetStreamEvent& event);protected:	ENetHost*		mHost;	ENetPeer*		mPeer;};#endif#include "ENetStream.h"#include "Packet.h"namespace ENet{	int	Init()			{ 		return enet_initialize(); 	}	void Deinit()		{ 		enet_deinitialize(); 	}};ENetStream::ENetStream() :	mHost(0),	mPeer(0){}bool ENetStream::Listen(int port){	ENetAddress address;    /* Bind the server to the default localhost.     */    /* A specific host address can be specified by   */    /* enet_address_set_host (& address, "x.x.x.x"); */    address.host = ENET_HOST_ANY;    address.port = port;    mHost = enet_host_create (& address /* the address to bind the server host to */,                                  32      /* allow up to 32 clients and/or outgoing connections */,                                  0      /* assume any amount of incoming bandwidth */,                                  0      /* assume any amount of outgoing bandwidth */);	return mHost != 0;}bool ENetStream::Connect(const char* server, int port){    mHost = enet_host_create (NULL /* create a client host */,                1 /* only allow 1 outgoing connection */,                57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,                14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);    if (mHost == NULL)		return false;	ENetAddress address;    ENetEvent event;    /* Connect to some.server.net:1234. */    enet_address_set_host (& address, server);    address.port = port;    /* Initiate the connection, allocating the two channels 0 and 1. */    mPeer = enet_host_connect (mHost, & address, 2);            if (mPeer == NULL)		return false;    /* Wait up to 5 seconds for the connection attempt to succeed. */    if (enet_host_service (mHost, & event, 5000) > 0 &&        event.type == ENET_EVENT_TYPE_CONNECT)    {        return true;    }    /* Either the 5 seconds are up or a disconnect event was */    /* received. Reset the peer in the event the 5 seconds   */    /* had run out without any significant event.            */    enet_peer_reset (mPeer);	return false;}void ENetStream::Disconnect(){	enet_host_destroy(mHost);	mHost = 0;}bool ENetStream::Send(Packet* packet){	if (packet->GetPeer())		return enet_peer_send(packet->GetPeer(), packet->GetChannel(), packet->mPacket) == 0;		enet_host_broadcast(GetENetHost(), packet->GetChannel(), packet->mPacket);	return true;}bool ENetStream::Receive(Packet* packet){	return true;}bool ENetStream::GetEvent(NetStreamEvent& event){	ENetEvent eEvent;	if (enet_host_service(GetENetHost(), &eEvent, 0) <= 0)		return false;	switch (eEvent.type)	{	case ENET_EVENT_TYPE_CONNECT:		event.type = NET_Connect;		event.peer = eEvent.peer;		break;	case ENET_EVENT_TYPE_RECEIVE:		event.type = NET_ReceivePacket;		event.peer = eEvent.peer;		event.packet = Packet(SO_Read, true, eEvent.channelID, event.peer);		event.packet.mPacket = eEvent.packet;        		break;       	case ENET_EVENT_TYPE_DISCONNECT:		event.type = NET_Disconnect;		event.peer = eEvent.peer;		break;	}	return true;}void ENetStream::ReleaseEvent(NetStreamEvent& event){	event.packet.Release();}#ifndef _PACKET_H_#define _PACKET_H_enum StreamOperation{	SO_Read,	SO_Write,};class Packet{	friend class ENetStream;public:	Packet(StreamOperation operation = SO_Read, bool reliable = true, int channel = 0, ENetPeer* peer = 0) :		mPacket(0),		mReliable(reliable),		mCreated(false),		mReadCursor(0),		mOperation(operation),		mPeer(peer),		mChannel(channel)	{	}	~Packet()	{		if (mCreated)		{			Release();		}	}	// maybe i should change this to c++	// ie. myPacket << myMatrix	// myPacket << myFloat	// this will handle compression etc..	// then i could change my whole file system to be like this to make streams easier to deal with	int Append(const void* data, unsigned int size)	{		if (!mPacket)		{			mCreated = true;			mPacket = enet_packet_create(data, size, mReliable ? ENET_PACKET_FLAG_RELIABLE : 0);		}		else		{			int curSize = mPacket->dataLength;			enet_packet_resize(mPacket, mPacket->dataLength + size);			memcpy(mPacket->data + curSize, data, size);		}		return size;	}	int Read(void* data, unsigned int size)	{		int readSize = min(size, mPacket->dataLength - mReadCursor);		memcpy(data, mPacket->data + mReadCursor, readSize);		mReadCursor += readSize;		return readSize;	}	StreamOperation GetStreamOperation()	{		return mOperation;	}	void SetStreamOperation(StreamOperation operation)	{		mOperation = operation;	}	int	GetChannel()	{		return mChannel;	}	int SetChannel(int channel)	{		mChannel = channel;	}	ENetPeer* GetPeer()	{		return mPeer;	}	void SetPeer(ENetPeer* peer)	{		mPeer = peer;	}	void Release()	{		if (!mPacket)			return;		enet_packet_destroy(mPacket);		mPacket = 0;	}//protected:	int				mChannel;	ENetPeer*		mPeer;	ENetPacket*		mPacket;	bool			mReliable;	bool			mCreated;	unsigned int	mReadCursor;	StreamOperation	mOperation;};template <class T>Packet& operator &(Packet& packet, T& data){	switch (packet.GetStreamOperation())	{	case SO_Read:		packet.Read(&data, sizeof(T));		break;	case SO_Write:		packet.Append(&data, sizeof(T));		break;	}    return packet;}#endif#include <iostream>#include <string>#include "ENet/ENetStream.h"#include "ENet/Packet.h"#include <winsock.h>#include <winsock2.h>#include <windows.h>#include <boost/function.hpp>using namespace std;// http://enet.cubik.org/Tutorial.htmlstruct Message{	float type;};struct TestNetworkMessage : public Message{	float value1;	float value2;	float value3;};Packet& operator &(Packet& packet, TestNetworkMessage& data){	if (packet.GetStreamOperation() == SO_Write)		packet = operator& (packet, *(static_cast<Message*>(&data)));	packet & data.value1;	packet & data.value2;    return packet;}void Server(){	ENetStream stream;	bool connect = stream.Listen(1234);	//ENetEvent event;    	while (1)	{		NetStreamEvent event;		while (stream.GetEvent(event))		{			switch (event.type)			{			case NET_Connect:				{					printf("A new client connected\n");					Packet p(SO_Write, true);					TestNetworkMessage test;					test.value1 = 5.0f;					p & test;					stream.Send(&p);				}				break;			case NET_Disconnect:				printf("A client disconnected\n");				break;			case NET_ReceivePacket:				{					printf("A packet has been received\n");					Message messageTest;					event.packet & messageTest;					TestNetworkMessage test;					event.packet & test;				}				break;			}		}	}}void Client(){	ENetStream stream;	bool connect = stream.Connect("192.168.1.60", 1234);	if (!connect)		return;	printf ("Connection successful.\n");	Packet p(SO_Write, true);	TestNetworkMessage test;	test.value1 = 5.0f;	p & test;	stream.Send(&p);	ENetEvent event;	while (1)	{		NetStreamEvent event;		while (stream.GetEvent(event))		{			switch (event.type)			{			case NET_Connect:				printf("A new client connected");				break;			case NET_Disconnect:				printf("A client disconnected");				break;			case NET_ReceivePacket:				printf("A packet has been received");				break;			}		}	}}int main(int argc, const char* args[]){	if (ENet::Init())    {        fprintf (stderr, "An error occurred while initializing ENet.\n");        return EXIT_FAILURE;    }	Packet p(SO_Write, true);	TestNetworkMessage test1;	test1.value1 = 5;	test1.value2 = 3;	test1.value3 = 1;	p & test1;	p.SetStreamOperation(SO_Read);	TestNetworkMessage test2;	p & test2;	if (argc >= 2 && strcmpi(args[1], "server") == 0)		Server();	else		Client();	ENet::Deinit();	return 0;}
supagu
supagu
i figured it out! i was deleting the packet after calling send on it

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.