tcp客户端参考代码如下:
import socket
def main():
"""tcp客户端"""
# 创建套接字
client_soc = socket.socket()
client_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 建立链接
client_soc.connect(("127.0.0.1", 1234))
# 收发消息
send_msg = input("请输入要下载的文件名称:")
client_soc.send(send_msg.encode("utf-8"))
recv_msg = client_soc.recv(1024*1024*50)
with open("new"+send_msg, 'wb') as f:
f.write(recv_msg)
# 关闭套接字
client_soc.close()
if __name__ == '__main__':
main()
tcp服务器端参考代码如下:
import socket
def main():
"""tcp服务器端"""
# 创建套接字
serv_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 帮顶ip地址
serv_soc.bind(("127.0.0.1", 1234))
# 设置监听模式
serv_soc.listen(128)
# accept
client_soc, client_addr = serv_soc.accept()
recv_msg = client_soc.recv(1024).decode("utf-8")
try:
with open(recv_msg, "rb") as f:
content = f.read()
except Exception:
print("没有该文件")
else:
client_soc.send(content)
client_soc.close()
# 关闭套接字
serv_soc.close()
if __name__ == '__main__':
main()