Python3 socket同步通信简单示例

时间:2021-07-07 15:43:07

本文实例讲述了Python3 socket同步通信。分享给大家供大家参考,具体如下:

本文比较简单,适合入门用,作个笔记,方便日后抄写

一个服务端,一个客户端,而且是阻塞方式,一次只能接受一个客户端连接并通信噢。

客户端发送‘bye', 结束与服务端的通信,如果发送'shutdown',服务端将会关闭自己!

服务端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

客户端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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()

希望本文所述对大家Python程序设计有所帮助。