python3簡單的服務器和客戶端例子多進程

服務器端 

#!/usr/bin/env python3

from socket import *
from time import ctime
import multiprocessing

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = HOST, PORT

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)



def worker(tcpCliSock,addr):
    tcpCliSock, addr = tcpCliSock, addr
    print('...connected from:', addr)
    while True:
        data = tcpCliSock.recv(BUFSIZ)
        if not data:
            break
        print(data.decode()+ctime())
        tcpCliSock.send(ctime().encode() + b'#' + data)
    tcpCliSock.close()


try:
    jobs=[]
    while True:
        print('waiting for connection...current %d task'%len(jobs))
        tcpCliSock, addr = tcpSerSock.accept()
        p=multiprocessing.Process(target=worker, args=(tcpCliSock, addr))
        jobs.append(p)
        p.start()
except KeyboardInterrupt:
    print('byebye')
finally:
    tcpSerSock.close()

客戶端

#!/usr/bin/env python3

from socket import *

HOST = '根據實際修改'
PORT =	21567           
BUFSIZ = 1024
ADDR =HOST,PORT

tcpCliSock = socket(AF_INET,SOCK_STREAM)
try:
	tcpCliSock.connect(ADDR)
except Exception as e:
	print('Cannot connect the %s server'%HOST,e)
while True:
	data = input('> ')
	if not data:
		break
	tcpCliSock.send(data.encode())
	data = tcpCliSock.recv(BUFSIZ)
	if not data:
		break
	print(':'+data.decode())
tcpCliSock.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章