Skip to content

Instantly share code, notes, and snippets.

@g0ddest
Last active December 8, 2017 15:10
Show Gist options
  • Save g0ddest/e90652570581729f677b632d463da346 to your computer and use it in GitHub Desktop.
Save g0ddest/e90652570581729f677b632d463da346 to your computer and use it in GitHub Desktop.
class server:
# list of all TCP connections
tcp_connections = list<tcp_connection>
# one tcp_connection have limited count of connections
struct tcp_connection{
list<connection> connections
}
# status of logical connection
enum status{
OFFLINE, # client was disconnected, or never connected
ONLINE # client connected and found link with connection_id
}
# logical connection inside tcp connection linking two tox clients
struct connection {
# id of logical connection that returns to client
uint id, # id from 16 to 255
# PK's of tox clients
list<Pair<PK, status>> clients
}
uint get_free_index(tcp_connection tcp){
# find new unique index not placed in connection list
# it can be simple loop of all possible values with checking if this index in list:
# tcp.connections.contains(id)
}
connection create_new_connection(tcp_connection tcp, PK from, PK dest){
# when creating new link (logical connection) we set that requesting client is online
# and requested client is pending - offline
connection new_connection = new connection()
.id(get_free_index())
.clients{
.add(from, status.ONLINE)
.add(dest, status.OFFLINE)
};
# put new logical connection to list
tcp.connections.add(new_connection)
return new_connection
}
# when client connected he calls this to get a connection_id for requested PK to talk with
connection get_connection(tcp_connection tcp, PK from, PK dest){
# search exisiting connection in all connections
existing_connection = tcp.connections.filter( connect -> connect.clients.contains(from, dest) )
if existing_connection{
# if we found some pending connection
# change status of existing connection from to online
existing_connection.clients
.filter(key, current_status -> key == from && current_status == status.OFFLINE )
= new Pair<>(from, status.ONLINE)
# and then create our connection
# with dest ONLINE because we know that here is online pending connection with dest PK
new_connection = create_new_connection().clients.filter(key, current_status -> key == dest).status
= new Pair<>(dest, status.ONLINE)
# and push it into the current tcp_connection
return new_connection
}
# if here is no existing connections create new one with pending dest
return create_new_connection(from, dest)
}
boolean is_connection_online(connection connect){
# if here is more then one online client connection is online
return connect.clients.count(key, current_status -> current_status == status.ONLINE) > 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment