Host/Join system

Previous topic - Next topic

MrTAToad

Previously, GLBasic didn't allow network broadcasting - which made joining a networked program a bit of problem.  It was also how most commerical games didn't work...

Thus, I present a pretty generic Host/Join system, using UDP broadcasting.  At the moment, this is the first version, and so a few things are missing :


  • Drop-in/out
  • Abnormal disconnections
  • Joining via IP address entry

This is the host screen :


And this is the join screen :


And this is the code.  To run this you'll also need the Timing code from my website, but if you dont want to download it, the two functions of initAppTime and updateAppTime can be replaced.  You also need DDGui

The test code :
Code (glbasic) Select
// --------------------------------- //
// Project: TestHostJoinNetworkGame
// Start: Sunday, January 25, 2009
// IDE Version: 6.143

TYPE tPlayer
xPos
yPos
b1
b2
prevXPos
prevYPos
ENDTYPE

TYPE tListOfPlayers
ipAddress%
playerName$
arrayIndex%
player AS tPlayer
ENDTYPE

INPUT h$,100,100
IF h$="H"
hostJoinNetworkGame(TRUE,4,8)
ELSE
hostJoinNetworkGame(FALSE,4,8)
ENDIF

// This is called to initialise game
FUNCTION initialise:
ENDFUNCTION

// This is called to send all data to other computers
FUNCTION sendGameData:socket%,port%,thisIP%,thisIndex%,player AS tPlayer,listOfPlayers[] AS tListOfPlayers
LOCAL list AS tListOfPlayers
LOCAL temp$
LOCAL result%

temp$=NETMESSAGE_GAMEDATA$+SEPERATOR$+thisIP%+SEPERATOR$+player.xPos+SEPERATOR$+player.yPos%+SEPERATOR$+thisIndex%
FOREACH list IN listOfPlayers[]
IF list.ipAddress%<>thisIP%
DEBUG "Sending to : "+SOCK_GETIP$(list.ipAddress%)+" "+temp$+"\n"
result%=SOCK_UDPSEND(socket%,temp$,list.ipAddress%,port%)
IF result%<0
DDgui_msg(NETGETLASTERROR$(),FALSE)
ENDIF
ENDIF
NEXT
ENDFUNCTION

MrTAToad

#1
The main code is too big to fit here, so the file can be downloaded from my website here : http://www.nicholaskingsley.co.uk/linked/hostjoinnetworkgame.gbas

The main idea is that the main routine (setupDisplay) deals with everything - the broadcast system continually runs (so that clients can always see it), and a acknowledgement system is also running to help detect if a client (or host) leaves.

At the moment, the code that a user would need to provide to initialise a game is also in the routine, so that needs changing a bit.

The next thing to do is the drop-in code.  The idea being you can join a game in progress (if the server allows it).  To do this, all the current clients (and server) needs to know about the new client whilst the new client has to know about the existing clients, after which it can then be initialised.

Drop-out code is exactly the same as an abnormal client termination - when this happens all remaining clients (and the server) are notified, and a flag (to be added to the tListofPlayers type) is set so that the client can be ignored - or possibly even deleted.