python 中 socket 使用
socket 实现 tcp server
import socket soc=socket.socket() #默认 family=-1,type=-1, proto=-1, fileno=None ''' if fileno is None: if family == -1: family = AF_INET if type == -1: type = SOCK_STREAM if proto == -1: proto = 0 ''' soc.bind((ip,port)) # ip and port should in a tuple while 1: server.listen(6) remote_socket, remote_adder = server.accept() # res is a tuple contain cotain socket object and remote ip like (socket,remote_IP) print(remote_adder, remote_socket) while 1: time.sleep(0.01) try: res = remote_socket.recv(1024) if res: print(res.decode()) remote_socket.send(b'cmd mysql') res = remote_socket.recv(1024) if res: res = res.decode('utf-8') print(res) except ConnectionAbortedError: print('done') break
socket 实现 tcp client
import socket
socket =socket.socket()
socket_client=socket.connect((ip,port))
socket_client.send(b'Hello World')
socket_client.send('Action speak louder than words'.encode('ascii'))
socket_client.sendall('你好'.encode('gbk')
socket.setdefaulttimeout(10) #socket module invoke
socket_client.settimeout(10) # socket object invoke。