sockets - Python 3.4 listening to selected server and port -
this code can create socket, connect selected server , port, , print reply. have question, how can listening port longer 1 moment? e.g. want listen selected port 20 seconds , print packets come @ time. possible code?
import socket import sys try: s = socket.socket(socket.af_inet, socket.sock_stream) except socket.error msg: print("failed create socket. error code: " + str(msg[0]) + ' , error message : ' + msg[1]) sys.exit(); print('socket created') host = #server port = #port try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: print('hostname not resolved. exiting') sys.exit() print('ip address of ' + host + ' ' + remote_ip) s.connect((remote_ip , port)) print('socket connected ' + host + ' on ip ' + remote_ip) reply = s.recv(4096) print(reply)
you try setting timeout socket should fit requirement if understand correctly need wait 1 time 20 seconds.
s.settimeout(20) reply = s.recv(4096)
however not guaranteed data packets delivered @ once. mentioned in comment, should looping. way place socket in nonblocking mode.
outside of loop, need buffer_variable
hold total results recv().
prior entering loop, start timer. upon entering loop begin calling recv()
on socket while saving result in local_variable
. each time new in local_variable
append buffer_variable
.
when timer expires, break
loop, , process data buffer_variable
accordingly.
Comments
Post a Comment