Python socket学习笔记(二)
Socket 例子
server端
import socket HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(1) conn,addr = s.accept() print ('Connected by ',addr) while 1: data=conn.recv(1024) if not data:break conn.sendall(data) conn.close()
clinet 端
import socket HOST = '10.2.34.207' #server's IP PORT = 50007 #server's port s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) s.sendall('Hello World') data = s.recv(1024) s.close() print ('Received',repr(data))
效果演示
缺点:只能通信一次,下一步持续通信
服务器端:
import socket
HOST = ''
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)
data=conn.recv(1024)
if not data:break
print('data from :',addr,data)
conn.sendall(data)
conn.close()
效果演示:
下一步长连接设置:
修改client代码:
import socket
HOST = ''
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)
if not data:break
print('data from :',addr,data)
conn.sendall(data)
conn.close()
模拟 ssh协议
服务器
import socket,commands
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(4)
while 1:
conn, addr = s.accept()
print ('Connected by ', addr)
while 1:
data=conn.recv(1024)
if not data:break
print('Command received from :',addr,data)
cmd_status,result = commands.getstatusoutput(data)
if cmd_status == 0:
conn.sendall(result)
else:
conn.sendall("DONE")
conn.close()
客户端:
import socket,time,sys
HOST = 'localhost' #server's IP
PORT = 50007 #server's port
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
while 1:
cmd = raw_input("The command,e for exit:").strip()
if len(cmd) == 0: continue
elif cmd == 'e': sys.exit()
s.sendall(cmd)
data = s.recv(1024)
#time.sleep(2)
print (data)
s.close()
演示效果
解决了错误命令,客户端退出,空输入 等问题