Example explanation of socket synchronous communication in Python3

巴扎黑
Release: 2017-08-09 10:54:55
Original
1918 people have browsed it

This article mainly introduces the Python3 socket synchronous communication function, and analyzes the Python socket synchronous communication client and server-side implementation techniques in the form of simple examples. Friends in need can refer to it

The examples in this article describe Python3 socket synchronous communication. Share it with everyone for your reference, the details are as follows:

This article is relatively simple, suitable for beginners, make a note to facilitate future copying

One server, one client, and it is a blocking method. Only one client can be accepted to connect and communicate at a time.

The client sends 'bye' to end the communication with the server. If it sends 'shutdown', the server will shut down itself!

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
Copy after login

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()
Copy after login

The above is the detailed content of Example explanation of socket synchronous communication in Python3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template