Python socket programming

#Continuous communication, actually 1:1 TCP communication ************************************ ********************************

#Service-Terminal----------------------------------------------- ---------------------------------------

#coding=utf-8
#_author_='wxp'

import socket


sk = socket.socket()
sk.bind(("127.0.0.1", 9008))
sk.listen(5)
while True:
    conn, addr = sk.accept()
    while True:
        accept_data = str(conn.recv( 1024),
                          encoding="utf8")
        print("".join(["Receive content:", accept_data, "Client port:", str(addr[1])]))
        if accept_data == "byebye": # If "byebye" is received, it will jump out of the loop and end the communication with the first client, and start communicating with the next client
            break
        send_data = input("Enter the content to send: ")
        conn.sendall(bytes(send_data, encoding= "utf8"))

    conn.close() # End the communication when it jumps out of the loop

#Client--------------------------------------------------------- --------------------

#coding=utf-8
#_author_='wxp'
import socket


sk = socket.socket()
sk.connect(( "127.0.0.1" , 9008 ))   # Actively initialize the connection with the server
 while True :
    send_data = input ( "Enter the content to send:" )
    sk.sendall(bytes(send_data, encoding="utf8"))
    if send_data == "byebye":
        break
    accept_data = str(sk.recv(1024), encoding="utf8")
    print("".join(("接收内容:", accept_data)))
sk.close()
 
 

 
 
#Implement UDP communication similar to 1:N ========================================= ========

#Service-Terminal

#coding=utf-8
#_author_='wxp'
import socket

sk = socket.socket()
sk.bind(("127.0.0.1", 9008))
sk.listen(5)
dataCount=0

while True:
  print(' Data volume: %04d' % dataCount)
  print('Monitoring data....')
  conn, addr = sk.accept() #Blocking, waiting for data
  accept_data = str(conn.recv(1024),encoding="utf8" )
  print("Receive content: "+accept_data)
  print("Customer address: ", str(addr))
  send_data ='success'
  conn. sendall(bytes(send_data, encoding="utf8"))
  conn.close() # End the communication when it jumps out of the loop
  print('Receive end')
  dataCount+=1
  print('')


#client

import socket

sk = socket.socket()
sk.connect(( "127.0.0.1" , 9008 ))   # Actively initialize the connection with the server

 send_data = input ( "Input send content:" )
sk.sendall(bytes(send_data, encoding="utf8"))
accept_data = str(sk.recv(1024), encoding="utf8")
print("".join(("接收内容:", accept_data)))
sk.close()
print ( "Send finished" )

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325888484&siteId=291194637