InSim examples

From LFS Manual
Jump to navigationJump to search

Python

Example #1

How to connect, send a packet and receive the response.

# Import Python's socket module.
import socket

# Import Python's struct module, which allows us to pack and unpack strings.
import struct

# Initialise the socket in TCP mode. 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to LFS.
sock.connect(('localhost', 29999))

# Pack the IS_ISI data into a string.
isi = struct.pack('BBBBHHBcH16s16s', 
                  44,           # Size
                  1,            # Type
                  0,            # ReqI
                  0,            # Zero
                  0,            # UDPPort
                  0,            # Flags
                  0,            # Sp0
                  ' ',          # Prefix
                  0,            # Interval
                  'password',   # Admin
                  'MyProgram',) # IName

# Send the string to InSim
sock.send(isi)


# Some constants.
ISP_TINY = 3
TINY_NONE = 0

# keep alive the connection (see below)
def keepAlive(packet):
    # Check the packet type.
    if ord(packet[1]) == ISP_TINY:
        # Unpack the packet data.
        tiny = struct.unpack('BBBB', packet)
        # Check the SubT.
        if tiny[3] == TINY_NONE:
            # Send the keep alive packet back to LFS.
            sock.send(packet)


# We use a string as the buffer.
buffer = ''

while True:
    # Receive up to 1024 bytes of data.
    data = sock.recv(1024)

    # If no data is received the connection has closed.
    if data:
        # Append received data onto the buffer.
        buffer += data

        # Loop through each completed packet in the buffer. The first byte of
        # each packet is the packet size, so check that the length of the
        # buffer is at least the size of the first packet. 
        while len(buffer) > 0 and len(buffer) >= ord(buffer[0]):
            # Copy the packet from the buffer.
            packet = buffer[:ord(buffer[0])]

            # Remove the packet from the buffer.
            buffer = buffer[ord(buffer[0]):]

            # check keep alive!
            keepAlive(packet)

            # The packet is now complete! :)
            # doSomethingWithPacket(packet)
    else: 
        break

# Release the socket.
sock.close()