1.基于TCP/IP – IPv4的网络socket通信
处理流程:
sever.py
# This is a sample Python script.
# Press ?R to execute it or replace it with your code.
# Press Double ? to search everywhere for classes, files, tool windows, actions, and settings.
#coding=UTF-8
import socket
language = {'name:':'tom','how old are you':'25','bye':'bye!'}
HOST = "127.0.0.1"
PORT = 6666
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
print("Listing at port 6666")
conn,addr = s.accept()
print('Connect by:',addr)
while True:
data = conn.recv(1024)
data = data.decode()
if not data:
break
print('Received message :',data)
conn.sendall(language.get(data,'Nothing').encode())
conn.close()
s.close()
client.py
#coding=UTF-8
import socket
#language = {'name:':'tom','how old are you':'25','bye':'bye!'}
HOST = "127.0.0.1"
PORT = 6666
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#s.bind((HOST,PORT))
#s.listen(1)
try:
s.connect((HOST,PORT))
except Exception as e:
print('server not found!')
s.exit()
while True:
c = input('YOU say:')
s.sendall(c.encode())
data = s.recv(1024)
data = data.decode()
print('Received:',data)
if c.lower()=='再见':
break
s.close()
|