Python socket communication functions Introduction

 

Commonly used address family
AF_UNIX: file-based, communication between the different processes the same host
AF_INET: network-based, applies to IPv4
AF_INET6: network based on the use of IPv6


Common connection type
SOCK_STREAM: namely TCP / IP. Socket connection-oriented, reliable connection must be established prior to the communication. Providing a sequence of connection-oriented socket, reliable data delivery and will not be repeated, but with no record boundaries.
SOCK_DGRAM: namely UDP. Non-connection-oriented socket, without establishing a communication connection before. In the data transmission process can not guarantee the ordering of data, reliability and repeatability. However datagram indeed keeps a record of the border, meaning that data is sent as a whole, rather than cutting a plurality of segments in advance.


socket communication

end server 
Import Socket 
server = socket.socket () # default AF_INET, SOCK_STREAM 
server.bind (( " localhost " , 6868 )) to bind # host port number to a socket 
server.listen () # settings and start TCP listener 
the while True: 
conn, addr = server.accept () # passive acceptance of a TCP connection, the connection has been waiting to reach
 the while True: 
the Data = conn.recv ( 1024 ) # receive TCP messages, and set the maximum length
 IF not the Data: 
Print ( " disconnected " )
 BREAK 
conn.send (data.upper ()) of the received data # uppercase back to it 
server.close () 

Client terminal 
import socket 
Client = socket.socket() # 默认是AF_INET、SOCK_STREAM
client.connect(("localhost",6868))
while True:
s = input(">>")
client.send(s.encode("utf-8"))
data = client.recv(1024)
client.close()

 

socketserver module
using concurrent multi socketserver

import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
while True:
self.data = self.request.recv(1024)
if not self.data:
print("%s客户端连接已断开"%self.client_address)
break
self.request.sendall(self.data.upper())
if __name__ == "__main__":
server = socketserver.ThreadingTCPServer(("localhost",6969),MyServer) # 开启一个线程
server.serve_forever()

 


Reference:
https://www.jb51.net/article/145995.htm

Guess you like

Origin www.cnblogs.com/sea-stream/p/11210301.html
Recommended