I would you like write a client in python, that send packet to a TCP server.
I don't know the server implemantation, but it always return a menù like this (for example after
nc server 4444
Make your choice:
3- insert two numbers
3 (insert two numbers)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('connecting to host')
def send(self, command):
sock = self.connect()
recv_data = ""
data = True
print('sending: ' + command)
data = sock.recv(1024)
recv_data += data
print('received: ' + data)
connect = Connect()
if __name__ == "__main__":
1. Don't open and close the connection each time you use
send. We don't know the server implementation, but it's absolutely clear that server won't be able to say if it is the same client has reconnected or it's a new client. TCP simply has no tools for this. Even the client port number in your case is chosen randomly by your OS. Open the connection once and close it when you're done.
2. Your are likely to stuck here forever at some point:
while data: data = sock.recv(1024)
If the server has closed the connection, you may get an exception. If the server hasn't got anything to send, it will wait forever. Use
select to check if the server has sent you anything or use
settimeout + exception hadnling to make
recv wait for a certain time.
A quick non-select example of
sock.recv replacement of questionable quality:
def try_recv(sock, bufsize, timeout): old_timeout = sock.gettimeout() sock.settimeout(timeout) try: data = sock.recv(bufsize) except socket.timeout: data = None sock.settimeout(old_timeout) return data