// attempt to connect to ExampleNetwork as a client with the client name Client
networkId = JoinNetwork("ExampleNetwork", "Client")
// save the time that the connection attempt was made so that we can set a time out for connection failure
connectTime# = Timer()
// current connection state
// 0 = connecting, 1 = connected, -1 = network closed, -2 = connection failed
state = 0
do
// if a network is running, find the number of clients
clientNum = 0
if state >= 0
clientNum = GetNetworkNumClients(networkId)
endif
// if we are currently attempting to connect
if state = 0
Print("Connection Pending...")
// if the number of clients is greater than 1, the connection has succeeded
// this is because once connected, there must be a minimum of 2 clients (this machine and the host)
if clientNum > 1
state = 1 // indicate that we are now connected
// if the connection has not yet succeeded, check for a time out or an error
// if it takes longer than 5 seconds to connect, it is safe to assume that it has failed
// any time isnetworkactive returns 0 also indicates a failure
// reasons for failure might include there being no such network as ExampleNetwork
elseif Timer() - connectTime# > 5.0 or IsNetworkActive(networkId) = 0
state = -2 // indicate that the connection failed
// close the network so that we are free to attempt another connection
CloseNetwork(networkId)
endif
// if we are currently connected
elseif state = 1
// check that no errors have occured on the connection
if IsNetworkActive(networkId)
// print the network details and the details of this client
Print("Network Active")
Print("Network Clients Detected: " + Str(clientNum))
clientId = GetNetworkMyClientId(networkId)
Print("Server Id: " + Str(GetNetworkServerId(networkId)))
Print("Client Id: " + Str(clientId))
Print("Client Name: " + GetNetworkClientName(networkId, clientId))
else
Print("Network Inactive")
endif
// if the network has been closed deliberately, display a success message
elseif state = -1
Print("Network Closed")
// if the network connection has failed, display an error message
elseif state = -2
Print("Network Connection Failed")
endif
// if we are currently connected, give the user the opportunity to leave the network
if state = 1
Print("")
Print("Press Any Key To Close Network")
// if we are not currently connected, or trying to connect, give the user the opportunity to join the network
elseif state < 0
Print("")
Print("Press Any Key To Connect")
endif
// if any key has been released
if GetRawKeyReleased(GetRawLastKey())
// if we are currently connected
if state = 1
// disconnect from the network
CloseNetwork(networkId)
state = -1
// if we are not currently connected
elseif state < 0
// join the network
networkId = JoinNetwork("ExampleNetwork", "Client")
connectTime# = Timer()
state = 0
endif
endif
// update the screen
Sync()
loop
Help make AGK better by submitting an example for this command! (All examples are subject to approval)