Project for the XHacks Hackathon: 6/6/21-6/8/21. Aims to improve the Python 3 Socket library.
SimpleSockets aims to make it easier to send packets between programs. It acts as a wrapper for the built in socket library.
First, import the library:
import SimpleSocketsNext, initialize your client and specify the port you want to send from (this needs to match your server port):
SimpleSockets.initializeClient(1234)Now set your destination address:
address = ("192.168.1.9", 1234)
SimpleSockets.setDestination(address)Then let the server know a client is going to connect, then connect:
SimpleSockets.threadIncomingConnection()
connection = SimpleSockets.connectClient(address)Last, you'll actually send your packet. You don't need to repeat the setup process each time you send a packet.
SimpleSockets.sendPacketInt(connection, 9999)
SimpleSockets.sendPacketBool(connection, True)
SimpleSockets.sendPacketStr(connection, "Hello World!")Alternatively, you can queue your packets and send them all at once.
SimpleSockets.addPacketToQueue("int", 1234)
SimpleSockets.addPacketToQueue("bool", False, 5)
SimpleSockets.addPacketToQueue("str", "Hello! This packet was queued!", 16)
SimpleSockets.sendQueuedPackets(connection)Queued packets have the ability to be prioritized. This means you can add an important packet later in the queue, and it'll be sent earlier.
SimpleSockets.addPacketToQueue("str", "This is an important packet!", 36, SimpleSockets.QueuePriorities.HIGHEST)
SimpleSockets.addPacketToQueue("int", 69420, 8, SimpleSockets.QueuePriorities.HIGH)Queue priorities can be "LOWEST", "LOW", "NORMAL", "HIGH", or "HIGHEST". If you don't specify a priority it defaults to "NORMAL".
There are built in packet types for integers, booleans, and strings. An incoming packet looks like this: (3, 'int', b'1234').
- The first item in the tuple is the channel number.
- The second item in the tuple is the data type (can be 'int', 'bool', or 'string')
- The third item in the tuple is the byte data (decode this using UTF-8, or another encryption set using
SimpleSockets.setEncoding("<your encoding>")
You'll probably want to setup your own functions for dealing with packet data. By default, SimpleSockets will print this to the terminal if you have logging enabled (SimpleSockets.setLoggerState(True)). To set your own handler, use "monkey patching":
def handleData(data):
# Only log items on channel 3
if data[0] == 3:
Logger.log("Received data (type " + str(data[1]) + "): " + str(data[2].decode(SimpleSockets.getEncoding())))
SimpleSockets.handleReceivedData = handleDataWhen you're done, disconnect the client:
SimpleSockets.disconnectClient(connection)Run Client.py. It demonstrates the functions of this project.
You can run the file from your terminal: python Client.py.