SoFunction
Updated on 2024-11-12

Python socket how to implement server and client data transfer (TCP)

socket server and client data transfer (TCP)

Server-side:

import socket
# Create a socket object
socket_server = (socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999
#Binding Address
socket_server.bind((host, port))
#Setup Listening
socket_server.listen(5)
# socket_server.accept() returns a tuple, element 1 is the client's socket object, element 2 is the client's address (ip address, port number)
client_socket, address = socket_server.accept()
#while loops are meant to keep the conversation going
while True:
	# Receive client requests
    recvmsg = client_socket.recv(1024)
    # Decode the received data
    strData = ("utf-8")
    #Set exit conditions
    if strData == 'q':
        break
    print("Received: %s" % strData)
    # Input
    msg = input("Send:")
    #Send data, need to encode
    client_socket.send(("utf-8"))
#Shut down the server side
socket_server.close()

Client:

import socket
# Create a socket object
client = (socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999
# Connect to the server
((host, port))
while True:
    send_msg = input("Send:")
    #Set exit conditions
    if send_msg == "q":
        break
    send_msg = send_msg
    #Send data, encoded
    (send_msg.encode("utf-8"))
    # Receive data returned by the server
    msg = (1024)
    #Decode
    print("Received: %s", % ("utf-8"))
# Close the client
()

flow chart


在这里插入图片描述

socket server, client communicate with each other

Use socket to pass parameters to combine a running program with a client, starting the server first and then the client. The base code is as follows:

Server-side code

import socket
import time
print("Server on.")
#create sockets
mySocket = (socket.AF_INET, socket.SOCK_STREAM)
#Set IP and port
#host = ()
host = '127.0.1.1'
port = 3333
#bind binds the port
((host, port))
#Listening
(10)
while True:
    # Receive client connections
    print("Waiting to connect ....")
    client, address = ()
    print("New Connections")
    print("IP is %s" % address[0])
    print("port is %d\n" % address[1]) 
    while True:
        #Send a message
        msg = input("server-side send:")
        ((encoding='utf-8'))
        print("Sending complete.")
        print (('%Y-%m-%d %H:%M:%S',(())))# Formatting timestamps to standard format
        if msg == "EOF":
            break
        if msg == "quit":
            ()
            ()
            print("End of program\n")
            exit()
        
        #Read the message
        msg = (1024)
        print("Server Received:",("utf-8"))# Decode the received data
        print("Reading complete.")
        if msg == b"EOF":
            break
        if msg == b"quit":
            ()
            ()
            print("End of program\n")
            exit()

Client Code:

import socket
print("Client on.")
#create sockets
mySocket = (socket.AF_INET, socket.SOCK_STREAM)
# Set ip and port
#host = ()
host = '127.0.1.1'
port = 3333
 
try:
    ((host, port)) ## Connect to the server
    print("Connecting to the server.")
except :                           ## Connection unsuccessful, run initial ip
    print ('Connection unsuccessful')
 
while 1:
    #Receive messages
    msg = (1024)  
    print("Client received: %s" % ("utf-8"))# Decode the received data
    print("Reading complete.")	
    if msg == b"EOF":
        break
    if msg == b"quit":
        ()
        print("End of program\n")
        exit()
    
    #Send a message
    msg = input("Client sends:")
    ((encoding='utf-8'))
    print("Sending complete.")
    if msg == "EOF":
        break
    if msg == "quit":
        ()
        print("End of program\n")
        exit()       
print("End of program\n")

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.