Python3 writes an example tutorial on C and S network programs

  • 2020-04-02 14:00:26
  • OfStack

In this paper, an example of python3 to write C/S network program implementation. Specific methods are as follows:

The example described in this article is a C/S small program written according to wingIDE's prompt, the specific code is as follows:

The code of client side myclient.py is as follows:


#!/bin/env python
#-*- coding:gb18030 -*-
#
import socket 
import time

i=1
while i<10:
  address=("127.0.0.1",3138)
  s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(address)
  buf='N:%d' % i
  s.send(buf.encode()) # Note that in python3.0 Where network sending must be in byte string format, for example s.send(b"abc")
  buff=s.recv(1024)
  if(len(buff)):
    print(buff) 
  s.close
  time.sleep(1)
  i+=1

The code of server side myserver.py is as follows:


#!/bin/env python
#-*- coding:gb18030 -*-
#
import socket
address=('127.0.0.1',3138)
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(10)
while True:
  cfd,address=s.accept()
  buf=cfd.recv(1024)
  print(buf,address)
  cfd.send(buf)
  cfd.close()

It is hoped that the example in this paper can be a reference to the Python network programming.


Related articles: