python利用Socket传输字符实现

写了一个程序, 原理就是服务器端启动一个server等待接受文件, 客户端通过socket连到server上,然后send文件。适合初学者采纳:

服务器代码:

import socket
import threading
import time
import sys

def socket_service():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 防止socket server重启后端口被占用(socket.error: [Errno 98] Address already in use)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((‘127.0.0.1’, 8888))
s.listen(5)
except socket.error as msg:
print (msg)
sys.exit(1)
print(b’Waiting connection…’)

while 1:
    conn, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(conn, addr))
    t.start()

def tcplink(conn, addr):
print(‘Accept new connection from %s:%s…’ % addr)
conn.send(‘Welcome!’)
while True:
data = conn.recv(1024)
time.sleep(1)
if not data or data.decode(‘utf-8’) == ‘exit’:
break
conn.send((‘Hello, %s!’ % data.decode(‘utf-8’)).encode(‘utf-8’))
conn.close()
print(‘Connection from %s:%s closed.’ % addr)

if name == ‘main‘:
socket_service()

客户端代码:‘
import socket
import sys

def socket_client():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((‘127.0.0.1’, 8888))
except socket.error as msg:
print(msg)
sys.exit(1)
print(s.recv(1024).decode(‘utf-8’)) # 打印b‘welcome
while 1:
data = input(‘please input work: ‘)
s.send(data.encode(‘utf-8’))
print(s.recv(1024).decode(‘utf-8’))
if data == ‘exit’:
break
s.close()

if name == ‘main‘:
socket_client()
需要注意的是:如果是在windows系统下运行,两个程序不能同时在python上运行,否侧会发生主机积极拒绝的问题,一个在Python下运行,一个在cmd运行即可。
运行结果:
python利用Socket传输字符实现_第1张图片

你可能感兴趣的:(python利用Socket传输字符实现)