This python module is for creating a tcp client. The code allows for the client to receive and send ints,shorts, and strings. The messages are formated in the way that there are two bytes before the actual contents of the message. The first byte is the size of the message and the second is a null byte.
- Successfully import the module into your python project
fromclientNetimport*- Connect to your server
sock=tcp_connect("127.0.0.1",3000)Note: An exception will be thrown if the connection fails. Also tcp_connect returns a socket object that you must keep to be able to send and receive messages.
- Read or write messages
packet_cases= {
0 : function1,
1 : function2
}
deffunction1:#func 1 is going to be if string was receivedprint(readstring())
deffunction2:#func 2 is going to be if int was receivedprint(str(readint())if (receivemessage(sock) >0):
packetID=readbyte() #it is helpful to have the first byte of your message be what type of message it ispacket_cases[packetID]()defsendString(text):
globalsockmessageid=0clearbuffer() #always want to clearbuffer before sending new messagewritebyte(messageid)
writestring(text)
sendmessage(sock)