python socket

TCP

 

Server

'' ' 
Server Server 
' '' 

Import socket 
SK = socket.socket () 
sk.bind (( " 127.0.0.1 " , 8898)) # to bind to a socket address 
sk.listen () # monitor link 
conn , addr = sk.accept () # receiving client link 
RET = conn.recv (1024) # receiving client information 
Print (RET) # print client information 
conn.send (B ' Hi ' ) # sends a message to the client 
conn.Close () # close the client socket 
sk.close () # close the server socket

 

Client

'' ' 

Client-side 
' '' 
Import socket 
SK = socket.socket () # create client socket 
sk.connect (( ' 127.0.0.1 ' , 8898)) # try to link server 
sk.send (b ' the Hello ' ) 
RET = sk.recv (1024) # receiving message 
Print (RET) 
sk.close () # close the client socket

 

UDP

'' ' 
Server Server 
udp 
' '' 

Import socket 
udp_sk = socket.socket (of the type = socket.SOCK_DGRAM) # create a server socket 
udp_sk.bind (( " 127.0.0.1 " , 9000)) # Bind server sets Sockets 
MSG, addr = udp_sk.recvfrom (1024 )
 Print (MSG) 
udp_sk.sendto (B ' Hi ' , addr) # dialogue 
udp_sk.close ()

 

Client

'''

client端
udp
'''
import socket
ip_port=('127.0.0.1',9000)
udp_sk=socket.socket(type=socket.SOCK_DGRAM)
udp_sk.sendto(b'hello',ip_port)
back_msg,addr=udp_sk.recvfrom(1024)
print(back_msg.decode('utf-8'),addr)

 

Guess you like

Origin www.cnblogs.com/huay/p/11087949.html