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

Python Experiment 8 network programming

編輯:Python

2022.6.10 Afternoon Experiment 8

Experiment 8 Network programming

List of articles

    • Preface
    • subject

Preface

This article is 【Python Language foundation 】 Column articles , Mainly the notes and exercises in class
Python special column Portal
The experimental source code has been in Github Arrangement

subject

Using a TCP or UDP Socket to write an intelligent chat robot program

Problem analysis

TCP Work requires connection 、 Data connection 、 Three steps to disconnect . utilize socket modular , Design server and client , By setting IP And port number . Build a thesaurus on the server , The client sends a message to the server , After the server matches the thesaurus, it returns to the client and outputs

socket Modules are commonly used for TCP Programming methods :

socket.socket: Create socket

serverSocket.bind((IP, Port)) : Bind socket

connect(address): Connect to a remote computer

send(bytes[,flags]): send data

recv(bufsize[,flags]): receive data

bind(address): Binding address , It is usually used on the server

listen(backlog): Start listening , Wait for the client to connect

accept(): Respond to client requests

Code

Simple version of

# server.py
''' Run the server first and then the client '''
""" @Author: Zhang Shier @Date:2022 year 06 month 15 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
import socket
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # Create socket 
serverSocket.bind(('127.0.0.1',12345)) # Bind socket 
print(" stay 12345 Port binding UDP...")
answers = [" Galileo , Copernicus "," Edison , tesla "," Nobel , mendeleev "] # Answer list 
i = 0
while True:
question,addr = serverSocket.recvfrom(1024) # Receive client information 
print(" The client asks :",question.decode()) # Problems with output reception 
# Send data to client 
serverSocket.sendto(bytes(" The server answers :" + answers[i],encoding='utf8'),addr)
i = i + 1
serverSocket.close() # Close socket 
# client.py
""" @Author: Zhang Shier @Date:2022 year 06 month 15 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
import socket
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # Create socket object 
questions = [' Who is the greatest astronomer in the world ?',' Who is the greatest inventor in the world ?',
' Who is the greatest chemist in the world ?'] # List of questions 
# Traverse the send list questions Problems in 
for question in questions:
# Send questions to the server 
clientSocket.sendto(bytes(question,encoding='utf8'),('127.0.0.1',12345))
print(" The client asks :" + question) # Output send problem 
answer,addr = clientSocket.recvfrom(1024) # The receiving server replies 
print(str(answer.decode())) # Output answers 
clientSocket.close() # Close socket 

Slightly optimized , You can roughly judge the reply to similar messages

# server.py
""" @Author: Zhang Shier @Date:2022 year 06 month 08 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
''' Optimize non original , link :http://t.csdn.cn/DOI0V'''
''' Run the server code first , Then run the client '''
import socket
from os.path import commonprefix
# Build a chat reply Dictionary 
words = {
'What is your name': 'Zhangshier',
'how are you?': 'Fine,thank you!',
'how old are you?': '18 forever',
'bye': 'Bye!'}
# Server host IP Address and port number , An empty string indicates any... Available locally IP Address 
HOST = "192.168.43.214"
PORT = 50007
# Use IPV4 agreement , Use tcp Protocol transfer data 
s = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
# Bind port and port number 
s.bind ( (HOST, PORT) )
# Start listening , Specifies that up to 1 Client connection 
s.listen ( 1 )
print ( ' The current listening port number is :', PORT )
conn, addr = s.accept ()
print ( ' Currently connected IP The address is :', addr )
# Start talking 
while True:
# Up to 1024 Bit size content , And decoding 
data = conn.recv ( 1024 ).decode ()
# If it's empty , sign out 
if not data:
break
print ( ' Received content :', data )
# Try to guess what the other person means 
m = 0
key = ''
for k in words.keys ():
# Delete extra white space characters 
data = ' '.join ( data.split () )
# Very close to a key , Go straight back 
if len ( commonprefix ( [ k, data ] ) ) > len ( k )*0.7:
key = k
break
# Use the choice method , Select a key with a high degree of coincidence 
length = len ( set ( data.split () ) & set ( k.split () ) )
if length > m:
m = length
key = k
# Choose the right message to reply 
conn.sendall ( words.get ( key, 'Sorry,can\'t find your problem! ' ).encode () )
conn.close ()
# client.py
import socket
import sys
# Server host IP Address and port number 192.168.43.214
HOST = "192.168.43.214"
PORT = 50007
# Use IPV4 agreement , Use tcp Protocol transfer data 
s = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
try:
# Connect to server 
s.connect ( (HOST, PORT) )
except Exception as e:
print ( ' Can't find the server , Please try again later !' )
sys.exit ()
while True:
c = input ( ' Please enter the message you want to send :' )
# send data , Use UTF-8 To encode into bytecode 
s.sendall ( c.encode () )
# Receive data from the server , The maximum size is 1024 The bit 
data = s.recv ( 1024 )
# decode 
data = data.decode ()
print ( ' Reply received :', data )
if c.lower () == 'bye':
break
# Close the connection 
s.close ()

result


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