python tcp_server端
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import time
def send_receive(tcp_socket,list1):
while True:
try:
new_socket, client_addr = tcp_socket.accept()
except:
print("not is new client send...")
time.sleep(5)
else:
new_socket.setblocking(False)
list1.append(new_socket)
for i in list1:
try:
recv_data = i.recv(1024)
except:
print("not data send....")
time.sleep(5)
else:
if recv_data != None:
print("is data send here...")
time.sleep(5)
else:
list1.remove(i)
i.close()
def main():
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_socket.bind(("192.168.8.104", 8088))
tcp_socket.listen(128)
tcp_socket.setblocking(False)
list1 = list()
send_receive(tcp_socket,list1)
tcp_socket.close()
if __name__ == "__main__":
main()
tcp_client端
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
def main():
try:
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = input("请输入服务器的ip: ")
server_port = int(input("请输入服务器的端口: "))
ip_port = (server_ip, server_port)
tcp_socket.connect(ip_port)
while True:
num = input("(1)发送数据\t (2)退出程序\t : ").strip()
if num == "1":
send_data = input("请输入你要传的数据: ")
tcp_socket.send(send_data.encode("utf-8"))
print("等sever端发数据过来: ")
servers_data = tcp_socket.recv(1024)
print("server data is: %s" % servers_data.decode("utf-8") )
elif num == "2":
exit()
else:
print("输入错误")
except Exception as result:
print("unknown error: %s" %result)
finally:
tcp_socket.close()
if __name__ == "__main__":
main()
tcp服务端带文件下载功能:
import socket
def down_file_to_client(new_client, address_port):
while True:
recv_file = new_client.recv(1024).decode('gbk')
if not recv_file:
break
print("clietn %s down file is: %s " % (str(address_port), recv_file))
files = None
try:
f = open(recv_file, "rb")
files = f.read()
f.close()
except Exception as ret:
print("this is %s not exsit!" % recv_file)
if files:
new_client.send(files)
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.2.121", 8081))
server_socket.listen(128)
while True:
new_client, address_port = server_socket.accept()
down_file_to_client(new_client, address_port)
new_client.close()
server_socket.close()
if __name__ == "__main__":
main()