python實現socket通訊
阿新 • • 發佈:2019-02-08
- server端
import socket
import commands
HOST='10.13.7.2'
PORT=50007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
while 1:
conn,addr=s.accept()
print 'Connected by ',addr
while 1:
data=conn.recv(1024)
cmd_status,cmd_result=commands.getstatusoutput(data)
if len(cmd_result.strip())==0:
conn.sendall('Done.')
else:
conn.sendall(cmd_result)
conn.close()
- client端
import socket
HOST='10.13.7.2'
PORT=50007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
while 1:
cmd=raw_input("Please input cmd:" )
s.sendall(cmd)
data=s.recv(1024)
print data
s.close()