Python socket communication ~ simple example

socket programming steps

  1. The server creates a socket, binds the address and port, and then listens for incoming connections on the port. Once a connection comes in, it receives the incoming connection through the accept function.
  2. The client also creates a socket. Bind the remote address and port, then establish a connection and send data.

  

family Address family, used with the first parameter of the socket() function. There are mainly the following

  1. socket.AF_UNIX is used to communicate with processes under a single machine
  2. socket.AF_INET is used to communicate with the server, usually this is used.
  3. socket.AF_INET6 支持 IPv6

sockettype socket type, used with the second parameter of the socket() function, commonly used are

  1. socket.SOCK_STREAM default, used for TCP protocol
  2. socket.SOCK_DGRAM for UDP protocol

Server

import socket

server = socket.socket()
server.bind(('127.0.0.1', 6969))
server.listen()

#Start listening # conn is a connection instance generated by the client when the client connects and the server generates it 
conn, addr = server.accept() #Wait   for the session link # print(conn,addr) 
# You can print the contents of conn and addr 
#Received data 
data = conn.recv(1024 )
 #Print received data print ( ' recv: ' , data)
 #Return data 
conn.send(data.upper())

 

client

import socket
 #Declare the socket type and generate a socket connection object at the same time 
client = socket.socket() #Start
 connecting client.connect 
(( ' 127.0.0.1 ' , 6969 ))
 #Send message Note 3. The above version can only send binary data 
client .send(b ' test socket ' )
 #Receive data 
data = client.recv(1024 )
 #Print receive data 
print ( ' recv: ' , data)
 #Close the connection 
client.close()

 

Guess you like

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