程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

HNU network counting experiment: Experiment 2 network basic programming experiment (java\python3)

編輯:Python

What to say

I remember when I was doing the experiment, I was full of sleep , Because experiment one and experiment two are very different , I remember the afternoon before the acceptance , I'm still crazy about changing the code .

as everyone knows , I am a chicken with a heart for fishing , So my code is actually a code I modified on the basis of other people's code , Actually, in theory, I should bia The website of the blog for reference , But this is a long time ago. I can't find it …

The experiment purpose

Through this experiment , Learn to use Socket( Socket ) Design a simple network data receiving and sending program , Understand how application packets are transmitted through the transport layer .

Experimental content

Socket( Socket ) It's an abstraction layer , Applications send and receive data through it , It's like an application opening a file handle , It's the same as reading and writing data to stable memory . One socket Allow applications to be added to the network , And communicate with other applications in the same network . An application on a computer to socket The written information can be read by another application on another computer , vice versa .
Different types of socket Associated with different types of underlying protocol families and different protocol stacks in the same protocol family . Now? TCP/IP The main ones in the protocol family socket The type is stream socket (sockets sockets) And datagram socket (datagram sockets). The stream socket will TCP As its end-to-end protocol ( Bottom use IP agreement ), Provides a trusted byte stream service . One TCP/IP The socket represents the stream TCP One end of the connection . Datagram socket use UDP agreement ( The bottom layer also uses IP agreement ), Provides a " Do my best "(best-effort) Datagram service for , The application can send the longest message through it 65500 Bytes of personal information . One TCP/IP The socket consists of an Internet address , An end-to-end protocol (TCP or UDP agreement ) And a unique port number .

Write a simple chat Program , And can transmit documents to each other , Programming language is unlimited

client

# Client's chat
import socket
import sys
import os
ip_port = ('127.0.0.1',9998) # Use 9999 Will prompt to be occupied ?
sk = socket.socket()
sk.connect(ip_port)
container = {
'key':'','data':''} # Cutting of file path 
while True:
FLAG = input('0. Receive the file 1. Send a file 2. Send message \n')
sk.sendall(str(FLAG).encode('utf-8'))
if FLAG=='1': # Send a file , The original function 
path = input('path:') # The client enters the path of the file to be uploaded 
path = 'F:\\\\'+path #F Discoid test10031.txt
print(' Ha ha ha ha ha ha ha ',path) ##################test
file_name = os.path.basename(path) # Get the file name according to the path 
file_size=os.stat(path).st_size # Get file size 
Informf=(file_name+'|'+str(file_size)) # Packaging of the client 
sk.send(Informf.encode()) # Send filename and file size 
# In order to prevent sticking , After sending the file name and size , Wait for the server to receive , Until a signal is received from the server ( It indicates that the server has received )
msg=sk.recv(1024)
print(msg.decode())
send_size = 0
f= open(path,'rb')
Flag = True
while Flag:
if send_size + 1024 >file_size:
data = f.read(file_size-send_size)
Flag = False
else:
data = f.read(1024)
send_size+=1024
sk.send(data)
aaa = sk.recv(1024) # New receipt 
print(aaa.decode())
f.close()
elif FLAG=='0' : # receive 
message=sk.recv(1024)
print(message.decode(encoding='utf8'))
message = input('path: ')
message = str(message)
# send data Overweight 
sk.sendall(message.encode('utf-8'))
print(' Client waiting ...')
# Previous Srv
pre_data = sk.recv(1024).decode()
# Get request method 、 file name 、 file size 
file_name,file_size = pre_data.split('|') # Unpacking the server 
# Prevent sticking , Send a signal to the client .
sk.sendall(' received '.encode())
# The size of the received file 
recv_size = 0
file_dir = os.path.join('F:\\\\',message) # Download file path splicing #### That's right in theory 
print(' Hey, hey, hey, hey, hey ',file_dir)
f = open(file_dir,'wb')
Flag = True
while Flag:
# Not finished uploading ,
if int(file_size)>recv_size:
# Maximum reception 1024, May receive less than 1024
data = sk.recv(1024)
recv_size+=len(data)
# write file 
f.write(data)
# Upload finished , Then exit the loop 
else:
recv_size = 0
Flag = False
sk.sendall(' Download complete '.encode()) # New send 
print(' Successful reception ')
f.close()
#Srv thus 
else : # Send information 
print(' Start chatting ')
while True:
msg = input("> ")
if msg == 'stop':
sk.send('stop'.encode('utf-8')) # The client sends a stop message 
break
elif not msg:
continue
sk.send(msg.encode('utf-8')) # Client sends message 
rev_data = sk.recv(1024) # The client accepts the message 
if not rev_data:
break
print(' Server message :', rev_data.decode('utf-8'))
sk.close()

Server side

# Server side 
import socketserver
import os
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
print ('connected...')
while True:
order = conn.recv(1024).decode(encoding='utf8') # Add read 
print(' perform ',order)
if order == '1' : # Receive the file , The original task 
print(' The server is waiting ...')
pre_data = conn.recv(1024).decode()
# Get request method 、 file name 、 file size 
file_name,file_size = pre_data.split('|') # Unpacking the server 
# Prevent sticking , Send a signal to the client .
conn.sendall(' received '.encode())
# The size of the received file 
recv_size = 0
file_dir = os.path.join('D:\\\\',file_name) # Received file path splicing # Now that's right 
print(" Cheerleading ",file_dir) #####test
f = open(file_dir,'wb')
Flag = True
while Flag:
# Not finished uploading ,
if int(file_size)>recv_size:
# Maximum reception 1024, May receive less than 1024
data = conn.recv(1024)
recv_size+=len(data)
# write file 
f.write(data)
# Upload finished , Then exit the loop 
else:
recv_size = 0
Flag = False
conn.sendall(' Download complete '.encode()) # Add send 
print(' Upload successful ')
f.close()
if order == '0' : # Send a file 
conn.sendall(' The server is ready to send the file '.encode('utf-8'))
# The original Clt
#path = input('path:') # The client enters the path of the file to be uploaded 
path = conn.recv(1024).decode() # Here the path is read from the client 
#file_name = os.path.basename(path) # Get the file name according to the path 
file_name = os.path.join('D:\\\\', path) # Splicing ########### That's right in theory 
print(' Yeah, yeah, yeah ',file_name)
file_size=os.stat(file_name).st_size # Get file size 
Informf=(file_name+'|'+str(file_size)) # Package file name and file size 
conn.send(Informf.encode()) # send out 
# In order to prevent sticking , After sending the file name and size , Wait for the server to receive , Until a signal is received from the server ( It indicates that the server has received )
bbb=conn.recv(1024).decode()
print(bbb)
send_size = 0
f= open(file_name,'rb')
Flag = True
while Flag:
if send_size + 1024 >file_size:
data = f.read(file_size-send_size)
Flag = False
else:
data = f.read(1024)
send_size+=1024
conn.send(data)
conn.recv(1024) # New receipt 
f.close()
if order == '2' :
print(' Start chatting ')
while True:
data = conn.recv(1024) # Accept messages sent by the client 
print(' Client message :', data.decode('utf-8'))
if not data:
continue
elif data.decode() == 'stop':
print(' Stop chatting ')
break
message = input('> ')
conn.send(message.encode('utf-8')) # Client sends message 
instance = socketserver.ThreadingTCPServer(('127.0.0.1',9998),MyServer)
instance.serve_forever()

The main idea is through FLAG To determine the operation :
FLAG=='1’ It is time to send files
FLAG=='0’ When you receive a file
FLAG=='2’ The time is when information is sent to each other

Some weird output doesn't need to be cared about , At that time, a bug then de Don't come out , I just want to see which step cannot be executed through output …
Plain programmers often use the most plain methods to debug…
I really appreciate …


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved