客户机端
import socket
ip = "10.0.105.182" #服务器的
port = 5000 #对方的端口
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((ip,port))
def send_file():
file = input("请输入要发送的文件:")
filename = file.split("\\")[-1]
print(filename)
c.send(bytes(filename,encoding='utf8'))
with open(file,"rb") as f:
data = f.read()
c.send(data)
def get_file():
file = input("请输入你要下载的文件:")
c.send(bytes(file,encoding="utf8"))
filename = file.split("/")[-1]
with open(filename,"wb") as f:
f.write(c.recv(20000))
def send_common():
while True:
cmd = input("请输入命令:")
c.send(bytes(cmd,encoding="utf8"))
if cmd == "bye":
break
data = c.recv(1000)
print(str(data,encoding="utf8"))
def main():
while True:
cmd = input("请输入,common,getfile,sendfile,byebye:")
c.send(bytes(cmd,encoding="utf8"))
if cmd == "byebye":
break
elif cmd == "common":
send_common()
elif cmd == "getfile":
get_file()
elif cmd == "sendfile":
send_file()
else:
continue
c.close()
if __name__ == "__main__":
main()
服务器端
#!/usr/local/bin/python3
import socket
import os
ip = "10.0.105.182" #自己的ip
post = 5000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((ip,post)) #绑定ip和端口
s.listen(1) #启动监听
conn,addr = s.accept() #接受对方数据conn以链接状态实例化,addr对方地址
print(addr) #对方地址
def get_file():
filename = conn.recv(1000)
with open(str(filename,encoding='utf8'),"wb") as f:
f.write(conn.recv(20000))
def send_file():
file = conn.recv(1000)
print(file)
with open(str(file,encoding='utf8'),"rb") as f:
data = f.read()
conn.send(data)
def get_common():
while True:
data = conn.recv(1000)
if data == b"bye":
break
print(data)
f = os.popen(str(data,encoding="utf8"))
data = f.read()
if data:
conn.send(bytes(data,encoding="utf8"))
else:
conn.send(b"finish")
def main():
while True:
cmd = conn.recv(1000)
if cmd == b'byebye':
break
elif cmd == b"getfile":
send_file()
elif cmd == b'sendfile':
get_file()
elif cmd == b"common":
get_common()
else:
continue
conn.close()
s.close()
if __name__ == "__main__":
main()