When and where i have to process packet from StreamPeer ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tilican

HI,

I want to make a custom script or node who manage TCP connection and emit custom signal for things like recieve packet, connected, disconnected, like websocket signals do.

But where i have to put this script ? In autoload ? Or a node in Root Scene

And when i have to verify packet count ?
If i put it on _proccess a client with less FPS going to recieve and packet in much time then another client with 120 FPS ?

thx

:bust_in_silhouette: Reply From: adabru

Hi Tilican,

with custom signals I guess using a node in the scene is more convenient than an autoload script.

If you want a tcp server to be able to accept connections from other clients, I guess you’d use the TCP_Server class. Two possibilities come to my mind on how you can process packets: in a single thread per connection or with polling in the _process function like you suggested.

Pseudocode for thread per connection:

var server = TCP_Server.new()

func _init():
  sever.listen(12345)
  Thread.new().start(acceptConnectionsThread)

func acceptConnectionsThread():
  while game is running:
    if server.is_connection_available():
      Thread.new().start(serveClientThread, server.take_connection())

func serveClientThread(connection):
  while connection is valid:
    # read and write conn, emit signals

Pseudocode for dealing with connections in _process() (same thread as everything other):

var server = TCP_Server.new()
var connections = []

func _init():
  sever.listen(12345)

func _process():
  if server.is_connection_available():
    connections.push_back(server.take_connection())
  for conn in connections:
    # read and write conn, emit signals

If latency doesn’t matter I’d use the second one to save dealing with thread and decreasing mental complexity. A web server would be a valid example. If you want realtime-communication, you would most certainly need another thread, as 16ms (60Hz) / 8ms (120Hz) are rather much latency to start with when other protocols build upon it. You can also start just one single other thread and interleave communication there like in the second example above.

I hope this somehow helps.