Python implementation of multiplexing TCP LAN file transmission based on socket

Keywords: socket less Linux Vmware

Basic information of LAN transmission

1. What is Io?

⦁ definition

Data exchange in memory
Interaction with terminal: input, output
Interact with disk: read, write
Interact with the network: recv, send

① IO intensive: there is a large amount of IO in the program, while the CPU operation is less, CPU resource consumption is small, time-consuming and inefficient
② Calculation intensive: there are a lot of calculations in the operation, with less IO behavior, large CPU consumption and fast execution speed

⦁ blocking IO

Definition: blocking form formed due to some conditions not met during IO operation
Efficiency: blocking IO is a very low efficiency IO with simple logic.

⦁ non blocking IO

Definition: to change the blocked IO to non blocked state by modifying the IO property behavior
Modification method:
sockf.setblocking(bool)
Function: set socket to non blocking IO
Parameters: True for blocking, False for non blocking

Sockf.settimeout(sec)
Function: timeout detection, blocking waiting time, no blocking after timeout
Parameters: timeout in seconds

2.IO multiplexing

definition

Multiple IO events are monitored at the same time. When an IO event is ready, the IO is executed. In this way, multiple IO can be processed at the same time. To avoid one IO blocking that makes other IO unable to execute and improve IO execution efficiency.
Specific scheme: ① select: windows/linux/unix
②poll: linux/unix
③epoll: linux

select specific usage

① Import: from select import select
② Monitoring IO:
rs,ws,xs = select(rlist,wlist,xlist)
Function: monitor multiple IO events, block and wait for IO to occur
Parameters: rlist list, followed IO events waiting to occur
wlist list, IO events to be actively handled
xlist list, IO events to be handled in case of exception
Return value:
rs: list, IO in rlist
ws: list, quasi ready IO in wlist
xs: list, IO ready in xlist
③ Note:

  • If there is an IO event in wlist, select will immediately return to ws
    *In the process of handling the event, find the situation where the server is occupied for a long time, such as no dead cycle
    *IO multiplexing consumes less resources and has high efficiency
  • Socket get address method:
    sockfd.getpeername() returns a tuple: (ip,port)

3. Realize file transmission of multiplex LAN

server.py

from select import *
from socket import *#Import module
from FileOperation import *

ip_address = "0.0.0.0"#Set IPV4 address
port = 8097#Set port
num = 3#Set listening quantity
addrs = []

server = socket(
	family=AF_INET,
	type = SOCK_STREAM,
	proto = 0
	)

server.bind((ip_address,port))
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,True)
#SO_REUSEADDR refers to the reuse of a network address in a short time
server.listen(num)
print("server is listening to the port:%d"%port)
print("server can be connected for %d clients at the same time "%num)
print("------------------------------------")

rlist = [server]#Store the concerned and waiting IO events
wlist = []#Store active IO events
xlist = []#Store abnormal events


while True:
	rs,ws,xs = select(rlist,wlist,xlist)
	for i in rs:#Traverse the ready IO events. If the ready IO event i is equal to the server server, a client connects.
		if i is server:
			coon,addr = i.accept()#connect
			rlist.append(coon)
			print(addr,"is connected......")
			addrs.append(addr)
		else:#If i equals the connection socket type, receive
			data = i.recv(102400)#Block waiting to send message
			msg = data
			add_file("./vmware-1.exe",msg)
				
			if msg == "quit":#Client requires disconnection
				rlist.remove(i)
				i.close()
				continue
			else:
				i.send(b"ok")#Feedback OK information to the client
server.close()

client.py

from socket import *#Import socket library
import time
from FileOperation import *

global server_ip
global server_port

server_ip = "192.168.75.1"#Use cmd here to view the host ipv4 address
server_port = 8097

client = socket(
	family = AF_INET,
	type = SOCK_STREAM,
	proto = 0)


while True:
	try:#Exception when the server is not opened
		client.setsockopt(SOL_SOCKET,SO_REUSEADDR,True)
		client.connect((server_ip,server_port))
	except:
		print("Are you far away from the server? Try again after getting close!")
		server_ip = input("If ip Interface input error, please try again here:")
		server_port = input("If ip Port input error, please try again here:")
		print("Retrying...")
		print(server_ip)
		print(server_port)
	else:
		break

while True:
	msg,read_bool = open_file("vmware.exe")
	client.send(msg)
	if msg == "quit":
		break

	data = client.recv(1024)
	msg = data.decode()
	print("server:%s"%msg)


client.close()

FileOperation.py

def open_file(dir):
	ReadBool = None
	msg = None
	try:
		with open(dir,"rb")as f:
			msg = f.read()
	except:
		pass
	else:
		ReadBool = True

	return msg,ReadBool

def write_file(dir,message):
	WriteBool = None
	msg = None
	try:
		with open(dir,"wb+")as f:
			f.write(message)
			f.close()
	except:
		pass
	else:
		WriteBool = True

	return msg,WriteBool

def add_file(dir,message):
	AddBool = None
	msg = None
	try:
		with open(dir,"ab+")as f:
			f.write(message)
			f.close()
	except:
		pass
	else:
		AddBool = True

	return msg,AddBool

matters needing attention

  1. msg,read_bool = open_file("vmware.exe")
    It is a file contained in the author's computer. When using TCP transmission, remember to replace this place with a readable file in the computer, or the program will report an error
  2. server_ip = "192.168.75.1"
    This is converted to the ipv4 address of the server
  3. Open first server.py File, reopen client.py . It's better to run it on the command line

Operation effect

Posted by steelerman99 on Sat, 13 Jun 2020 21:27:21 -0700