Python Socket use instance

  • 2020-06-15 09:45:10
  • OfStack

Python is powerful in network communication. Learn the basic way of Socket communication

UDP communications:

Server:


import socket
port=8081
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# Receive from any sender on the specified port UDP data 
s.bind(('',port))
print(' Waiting for access ...')
while True:
  # receive 1 A data 
  data,addr=s.recvfrom(1024)
  print('Received:',data,'from',addr)

Client:


import socket
port=8081
host='localhost'
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto(b'hello,this is a test info !',(host,port))

Very simple. Here's the TCP approach:

Server:


#-*- coding: utf-8 -*-
from socket import *
from time import ctime

HOST=''
PORT=12345
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)

sock.bind(ADDR)

sock.listen(5)
while True:
  print('waiting for connection')
  tcpClientSock, addr=sock.accept()
  print('connect from ', addr)
  while True:
    try:
      data=tcpClientSock.recv(BUFSIZ)
    except:
      print(e)
      tcpClientSock.close()
      break
    if not data:
      break
    s='Hi,you send me :[%s] %s' %(ctime(), data.decode('utf8'))
    tcpClientSock.send(s.encode('utf8'))
    print([ctime()], ':', data.decode('utf8'))
tcpClientSock.close()
sock.close()

Client:


#-*- coding: utf-8 -*-
from socket import *

class TcpClient:
  HOST='127.0.0.1'
  PORT=12345
  BUFSIZ=1024
  ADDR=(HOST, PORT)
  def __init__(self):
    self.client=socket(AF_INET, SOCK_STREAM)
    self.client.connect(self.ADDR)

    while True:
      data=input('>')
      if not data:
        break
      self.client.send(data.encode('utf8'))
      data=self.client.recv(self.BUFSIZ)
      if not data:
        break
      print(data.decode('utf8'))
      
if __name__ == '__main__':
  client=TcpClient()

There is a problem with TCP mode above, it cannot exit. Ok, let's modify 1 so that this program can send quit command to exit:

Server:


#-*- coding: utf-8 -*-
from socket import *
from time import ctime
from time import localtime
import time

HOST=''
PORT=1122 # Set the listening port 
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)

sock.bind(ADDR)

sock.listen(5)
# Set exit criteria 
STOP_CHAT=False
while not STOP_CHAT:
  print(' Wait for access and listen on the port :%d' % (PORT))
  tcpClientSock, addr=sock.accept()
  print(' Accept connection, client address: ',addr)
  while True:
    try:
      data=tcpClientSock.recv(BUFSIZ)
    except:
      #print(e)
      tcpClientSock.close()
      break
    if not data:
      break
    #python3 use bytes , so I'm going to code it 
    #s='%s The message sent to me is :[%s] %s' %(addr[0],ctime(), data.decode('utf8'))
    # Date against date 1 The formatting 
    ISOTIMEFORMAT='%Y-%m-%d %X'
    stime=time.strftime(ISOTIMEFORMAT, localtime())
    s='%s The message sent to me is :%s' %(addr[0],data.decode('utf8'))
    tcpClientSock.send(s.encode('utf8'))
    print([stime], ':', data.decode('utf8'))
    # If the input quit( Ignore case ), Program exit 
    STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
    if STOP_CHAT:
      break
tcpClientSock.close()
sock.close()

Client:


#-*- coding: utf-8 -*-
from socket import *

class TcpClient:
  # Test, connect the machine 
  HOST='127.0.0.1'
  # Set the listening port 
  PORT=1122 
  BUFSIZ=1024
  ADDR=(HOST, PORT)
  def __init__(self):
    self.client=socket(AF_INET, SOCK_STREAM)
    self.client.connect(self.ADDR)

    while True:
      data=input('>')
      if not data:
        break
      #python3 The relay will be bytes So you have to code it 
      self.client.send(data.encode('utf8'))
      print(' Send a message to %s : %s' %(self.HOST,data))
      if data.upper()=="QUIT":
        break      
      data=self.client.recv(self.BUFSIZ)
      if not data:
        break
      print(' from %s Received message: %s' %(self.HOST,data.decode('utf8')))
      
      
if __name__ == '__main__':
  client=TcpClient()

Note: The above code is Python3.

conclusion

That is the end of this article on the use of Python Socket, I hope to help you. Those who are interested can continue to see other related topics on this site. If there is any deficiency, please let me know. Thank you for your support!


Related articles: