python TCP 简单示例
flyfish
版本 python3
server
import socket
host=''
port=12345
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
while 1:
print ("waiting for connection...")
clientsock,clientaddr=s.accept()
print("...connected from:",clientaddr)
while 1:
data=clientsock.recv(1024).decode()
if not len(data):
break
print(clientsock.getpeername()[0]+':'+str(data))
clientsock.sendall(data.encode())
clientsock.close()
s.close()
client
import socket
port=12345
host='localhost'
data=input('Input send message:')
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.send(data.encode())
while 1:
buf=s.recv(1024).decode()
if not len(buf):
break
print('server data:'+str(buf))
s.close()