A simple example of Python3 socket synchronous communication
- 2020-06-03 07:08:53
- OfStack
This article gives an example of Python3 socket synchronous communication. To share for your reference, specific as follows:
This article is simple, suitable for introduction, make a note, easy to copy in the future
1 server, 1 client, and is blocked, can only accept 1 client connection and communication at a time oh.
The client sends' bye' to end communication with the server. If it sends 'shutdown', the server will shut itself down!
Server code:
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
quit = False
shutdown = False
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connected from: ', addr)
while True:
data = tcpCliSock.recv(BUFSIZE)
data = data.decode('utf8')
if not data:
break
ss = '[%s] %s' %(ctime(), data)
tcpCliSock.send(ss.encode('utf8'))
print(ss)
if data == 'bye':
quit = True
break
elif data == 'shutdown':
shutdown = True
break
print('Bye-bye: [%s: %d]' %(addr[0], addr[1]))
tcpCliSock.close()
if shutdown:
break
tcpSerSock.close()
print('Server has been
Client code:
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('>')
if not data:
continue
print('input data: [%s]' %data)
tcpCliSock.send(data.encode('utf8'))
rdata = tcpCliSock.recv(BUFSIZE)
if not rdata:
break
print(rdata.decode('utf8'))
if data == 'bye' or data == 'shutdown':
break
tcpCliSock.close()
For more information about Python, please visit Python Socket Programming Skills summary, Python Data Structure and Algorithm Tutorial, Python Function Usage Skills Summary, Python String Manipulation Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Manipulation Skills Summary.
I hope this article has been helpful for Python programming.