Difference between revisions of "InSim examples"

From LFS Manual
Jump to navigationJump to search
Line 62: Line 62:
  
 
sock.close()</pre></big>
 
sock.close()</pre></big>
 
 
== Example #2 ==
 

Revision as of 11:37, 22 June 2009

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 packet 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)

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

while True:
    # We receive up to 1024 bytes in each receive call.
    data = sock.recv(1024)

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

        # Loop through each completed packet in the buffer. The first byte of
        # each packet is the packet size, so we 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]):]

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

sock.close()