This is a work in progress but thought I'd share these two scripts while they were still barebone. This is a very simple example of how to create a chat server and client using sockets. This server example will not send anything to the clients, only listen and display what it receives. The client will connect to the server and let you send a text-based message. More than likely I'll send byte arrays rather than rely on AGK's specific string function as that will allow me to create a more robust protocol for the chat service.
To test, simply compile the server then run the executable outside of AGK. You can then run the client code directly from the editor.
Server+ Code Snippet// Project: chat_server
// Created: 2024-12-31
// show all errors
SetErrorMode(2)
// set window properties
SetWindowTitle( "chat_server" )
SetWindowSize( 1024, 768, 0 )
SetVirtualResolution( 1024, 768 )
SetSyncRate(0, 0 )
UseNewDefaultFonts( 1 )
Type Socket
id as integer
msg as string
EndType
sockets as Socket[]
// Listen for connections from any IP v4 on port 80
listener = createSocketListener("anyip4", 80)
socket = 0
repeat
// Check for new connections
socket = getSocketListenerConnection(listener)
while socket > 0
s as Socket
s.id = socket
sockets.insert(s)
socket = getSocketListenerConnection(listener)
endwhile
// Show IP of connected clients followed by their last sent message
print("<<< Sockets >>>")
for i = 0 to sockets.length
print(GetSocketRemoteIP (sockets[i].id))
if getSocketBytesAvailable(sockets[i].id) > 4
sockets[i].msg = getSocketString(sockets[i].id)
endif
print(sockets[i].msg)
print("")
next i
Sync()
until getRawKeyPressed(27)
Client+ Code Snippet// Project: chat_client
// Created: 2024-12-31
// show all errors
SetErrorMode(2)
// set window properties
SetWindowTitle( "chat_client" )
SetWindowSize( 1024, 768, 0 )
SetVirtualResolution( 1024, 768 )
SetSyncRate(0, 0 )
UseNewDefaultFonts( 1 )
// Connect to the server
connection = connectSocket("10.0.1.38", 80, 3000)
doText = 0
repeat
if doText = 1
print("Enter your message below: ")
test$ = test$ + getCharBuffer()
print("> "+test$)
else
print("Press ENTER to send a message.")
endif
if getRawKeyPressed(13) = 1
if doText = 0
dotext = 1
test$ = ""
getCharBuffer()
else
dotext = 0
sendSocketString(connection, test$)
flushSocket(connection)
endif
endif
Sync()
until getRawKeyPressed(27)
deleteSocket(connection)
end