Python_20180504

TCP/IP is a reliable transport protocol, UDP is unreliable Action at the fourth transport layer

Socket: Also known as "socket", it is used to describe ip address and port. It is a handle of a communication chain. Applications usually make requests to or respond to network requests through "sockets".

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is that "everything is a file". Socket is an implementation of this mode. Socket is a special file, and some socket functions operate on it.

The socket module is for opening, reading, writing, and closing sockets on the server side and the client side.

 

socket_server:

#!/usr/bin/env python 
# encoding: utf-8
import socket #socket is a standard library
ip_port = ( '127.0.0.1' , 9999)

sk = socket.socket() # should declare whether it is TCP/IP or UDP
sk.bind(ip_port) # is a tuple
sk.listen( 5) # The maximum number of connections allowed is 5.

while True:
print( 'Server waiting...')
conn ,addr = sk.accept() #Calling this method will return two values
​​#conn is the instance created for the client, addr is the client's address
client_data = conn. recv( 1024) #recv data print( str(client_data , 'utf8') ,) conn. sendall( bytes( 'Don't answer, don't answer, don't answer, don't answer!!' , 'utf8'))


#Send data to the client
conn.close()



socket_client:
#!/usr/bin/env python
# encoding: utf-8
import socket
ip_port = ('127.0.0.1',9999)

sk = socket.socket()
sk. connect(ip_port)

sk.sendall(bytes('request to occupy the earth','utf8'))
server_reply = sk.recv(1024)
print(str(server_reply,'utf8'))

sk.close()



Guess you like

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