SoFunction
Updated on 2024-11-17

Python socket network programming TCP/IP server-client communication

Python socket network programming

Beginning to learn python, some time ago, I bought two books "python programming from entry to practice" "Python core programming third edition", the first book is mainly about some basic syntax and some basic methods of use, and the second book is a lot of in-depth, they seem to be half-understood, I just saw this part of the network programming, there are still a lot of not quite understand the place, but I think that through the I've been searching for information to learn, and I'm sure I'll be able to understand it sooner or later. .......

The main module used in this section is the socket module, where you can find the socket() function, which is used to create a socket object. Sockets also have their own set of methods, which enable socket-based network communication.

socket() module function

To create a socket, you must use the () function, which has the following general syntax

socket(socket_family, socket_type, protocol=0)

where socket_family is AF_UNIX or AF_INET, socket_type is SOCK_STREAM or SOCK_DGRAM, and protocol is usually omitted, default = 0.

So to create a TCP/IP socket, you can use the following call ().

tcpSock = (socket.AF_INET, socket.SOCK_STREAM)

Also create a UDP/IP socket and call it with the following method

udpSock = (socket.AF_INET, socket.SOCK_DGRAM)

Creating a TCP Server

The process of creating a TCP server is basically as follows, not really code

ss = socket()          # Create server sockets
    ()              # Sockets bound to addresses
    ()             #Listening for connections
    inf_loop:             #Server infinite loop
        cs = ()   # Accept client connections
        comm_loop:      # Communication loop
            ()/()   # Dialog (receive/send)
        ()        # Close client sockets
    ()            # Close server sockets (optional)

In practice, the basic process of creating a TCP server as described above, may be slightly different but the basic idea should be the same, the following is the real wear pieces of server code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from socket import *      # Introduce the socket attribute into the namespace

HOST = ''          #This identifies the bind() method as being able to use any available address.
PORT = 21571      # port number
BUFSIZ = 1024     # Buffer size, 1kb
ADDR = (HOST,PORT)   #address ????

tcpSerSocket = socket(AF_INET,SOCK_STREAM)    # Create tcp socket
(ADDR)           #Bind the address to the socket
(5)            # Set up and start socket listening

while True:        # Infinite loop, waiting for client to connect
  print('waiting for connection...')   
  tcpCliSocket,addr = ()    # Passively accept client connections
  print('...connected from:',addr)

  while True:      # Conversation loop, waiting for the client to send a message
    data = (BUFSIZ)   # Receive client messages
    if not data:     # If the message is blank, jump out of the dialog loop and close the current connection
      break
    (data)   # If a message is received, return the message to the client unchanged

  ()
()

Creating a TCP Client

As above, a simple non-code process

cs = socket()    # Create client sockets
    ()     # Trying to connect to the server
    comm_loop:     # Communication loop
        ()/()  # Dialog (send/receive)
    ()       # Close client sockets

Creating a client in practice also translates the above steps

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from socket import *

HOST = 'localhost'    # Hostname of the server
PORT = 21571     # port number
BUFSIZ = 1024     # buffer
ADDR = (HOST,PORT)   # Address

tcpCliSocket = socket(AF_INET,SOCK_STREAM)  # Create client sockets
(ADDR)     # Connect to the server

while True:        # Communication loop
  data = input('> ')    # Client input information
  if not data:   # If the input message is empty, the loop is jumped out and the communication is closed
    break

  data = (data)      
  (data)   # Send client information
  data = (BUFSIZ)   # Accepting server returns
  if not data:    # Close the communication loop if no information is returned by the server
    break
  print('get:',('utf-8'))

()

Of course, this is only the most basic communication, and about the host name, port number and so on is not very understandable for the time being, so far all I have done is to communicate on the same computer, and the port number needs to be the same, if different computers to communicate how to do it? I'm still just a noob .....

Thanks for reading, I hope this helps, and thanks for supporting this site!