InSim examples
From LFS Manual
Jump to navigationJump to searchPython
Example #1
How to connect, send a packet and receive the response.
# Dependencies. import socket import struct # Some constants. INSIM_VERSION = 4 BUFFER_SIZE = 2048 # Packet types. ISP_ISI = 1 ISP_VER = 2 ISP_TINY = 3 TINY_NONE = 0 # Initailise the socket in TCP mode. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to LFS. sock.connect(('localhost', 29999)) # Pack the ISI packet into a string. isi = struct.pack('BBBBHHBBH16s16s', 44, # Size ISP_ISI, # Type 1, # ReqI - causes LFS to send an IS_VER. 0, # Zero 0, # UDPPort 0, # Flags 0, # Sp0 0, # Prefix 0, # Interval 'password', # Admin '^3example') # IName # Send the ISI packet to InSim. sock.send(isi) buffer = '' while True: data = sock.recv(BUFFER_SIZE) if data: buffer += data # Loop through completed packets. while len(buffer) > 0 and len(buffer) >= ord(buffer[0]): # Copy the packet from the buffer and delete it. packet = buffer[:ord(buffer[0])] buffer = buffer[ord(buffer[0]):] # Check packet type. if ord(buffer[1]) == ISP_TINY: # Unpack the TINY packet and check it for keep-alive signal. size, type, reqi, subt = struct.unpack('BBBB', packet) if subt == TINY_NONE: sock.send(packet) elif ord(buffer[1]) == ISP_VER: # Unpack the VER packet and check the InSim version. size, type, reqi, _, version, product, insimver = struct.unpack('BBBB8s6sH') if insimver != INSIM_VERSION: print 'Invalid InSim version' break else: # InSim connection has been lost. break # Release the socket. sock.close()