Here's a simple python 3.x TCP server:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print(str(self.client_address[0]) + " wrote: " + str(self.data.decode()))
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
and client:
import socket
import sys
HOST, PORT = "localhost", 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
while( True ):
data = input("Msg: ")
if data == "exit()":
print("Exiting...")
sock.close()
exit();
sock.sendall(bytes(data, "utf-8"))
#numBytes = ....?
#print("Sent: " + str( numBytes ) + " bytes\n")
I can't figure out how to view the exact number of bytes that I send in a message. I can use len(data), but it doesn't account for the null terminator and such.... Is null terminator being sent as well, or is it irrelevant? I tried researching on an exact byte count of a sent/received message, but I couldn't find any python-specific documentation and only have seen examples of people using len(), which I don't think is exact...
Any ideas?