22import time
33from collections .abc import Callable
44from enum import IntEnum
5+ from ipaddress import ip_address
56from pathlib import Path
6- from socket import IPPROTO_TCP , TCP_NODELAY , socket
7+ from socket import AF_INET , AF_INET6 , IPPROTO_TCP , TCP_NODELAY
8+ from socket import socket as sock
79from threading import Thread
810
911from rlbot import flat
@@ -47,6 +49,8 @@ class SocketRelay:
4749 rendering_status_handlers : list [Callable [[flat .RenderingStatus ], None ]] = []
4850 raw_handlers : list [Callable [[flat .CorePacket ], None ]] = []
4951
52+ socket : sock | None = None
53+
5054 def __init__ (
5155 self ,
5256 agent_id : str ,
@@ -57,13 +61,9 @@ def __init__(
5761 self .connection_timeout = connection_timeout
5862 self .logger = get_logger ("interface" ) if logger is None else logger
5963
60- self .socket = socket ()
61-
62- # Allow sending packets before getting a response from core
63- self .socket .setsockopt (IPPROTO_TCP , TCP_NODELAY , 1 )
64-
6564 def __del__ (self ):
66- self .socket .close ()
65+ if self .socket is not None :
66+ self .socket .close ()
6767
6868 @staticmethod
6969 def _int_to_bytes (val : int ) -> bytes :
@@ -73,6 +73,8 @@ def _read_int(self) -> int:
7373 return int .from_bytes (self ._read_exact (2 ), "big" )
7474
7575 def _read_exact (self , n : int ) -> bytes :
76+ assert self .socket is not None , "Socket has not been established"
77+
7678 buff = bytearray (n )
7779 view = memoryview (buff )
7880
@@ -89,6 +91,7 @@ def read_message(self) -> bytes:
8991 return self ._read_exact (size )
9092
9193 def send_bytes (self , data : bytes ):
94+ assert self .socket is not None , "Socket has not been established"
9295 assert self .is_connected , "Connection has not been established"
9396
9497 size = len (data )
@@ -157,7 +160,13 @@ def connect(
157160 """
158161 assert not self .is_connected , "Connection has already been established"
159162
163+ # Check if the IP is IPv4 or IPv6 and configure the socket accordingly
164+ family = AF_INET if ip_address (rlbot_server_ip ).version == 4 else AF_INET6
165+ self .socket = sock (family )
160166 self .socket .settimeout (self .connection_timeout )
167+ # Allow sending packets before getting a response from core
168+ self .socket .setsockopt (IPPROTO_TCP , TCP_NODELAY , 1 )
169+
161170 try :
162171 begin_time = time .time ()
163172 next_warning = 10
@@ -238,6 +247,7 @@ def handle_incoming_messages(self, blocking: bool = False) -> MsgHandlingResult:
238247
239248 Second boolean returns true if there might be more messages to handle without a delay.
240249 """
250+ assert self .socket is not None , "Socket has not been established"
241251 assert self .is_connected , "Connection has not been established"
242252 try :
243253 self .socket .setblocking (blocking )
0 commit comments