Socket
# with a Socke t means "open a network Connection" # Open a Socket you need to know the IP address and port number of the destination computer, and then specify the protocol type. # tcp# actively initiates the connection is the client, the passive corresponding is server # 1. Create a TCP connection-based Socketimport sockets = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # af_inet refers to the IPV4 protocol. Sock_stream refers to a stream-oriented TCP protocol. # Initializes a socket instance and has not established a connection # 2. Connect to Server # Connect accepts the parameter is a tuple: (IP, Port). The input domain name can be automatically converted to an IP address via DNS. S.connect ((' www.sina.com.cn ', 80)) # 3. Send data send# The following data means: request to return the contents of the first page # TCP connections Create a two-way channel, both parties can send data to each other at the same time. However, who first sent after the hair, how to coordinate, according to the specific agreement to decide. For example, the HTTP protocol specifies that the client must send a request to the server before the server sends the data to the client. S.send (b ' get/http/1.1\r\nhost:www.sina.com.cn\r\nconnection:close\r\n\r\n ') # 4. Accept the data sent by the server # after sending the HTTP format request, you can then receive the data returned by the Sina server: buffer = []while true:d = S.recv (1024x768) # 1KB if D:buffer.app End (d) Else: # The data has been read or the connection is interrupted, return empty string breakdata = B '. Join (buffer) # This sentence means using null bytes to concatenate the byte list of buffer into A new byte string # b ' is an empty byte, join is a function of the list of connections, and buffer is a list of strings that are continually received # for example put [b ' ab ', B ' CD ', B ' ef '] into B ' abcdef ' # 5. After accepting the data, close Sockets.close () # The received data includes the HTTP header and the Web page itself # We just need to separate the HTTP headers from the Web page, print the HTTP headers, and save the contents of the Web page to the file: Header, html = data.split (b ' \r\n\r\n ', 1) print (Header.decode (' Utf-8 ')) with open (' sina.html ', ' WB ') as File:file.write (HTML )
Server
# 1. The server process binds to a port and listens for a connection from the client # Four tuples to uniquely determine a socket# because the server is requesting multiple clients at the same time, each connection requires a new process or thread to process. # Let's write a simple server program that receives a client connection and sends a string of strings from the client to Hello and back again. Import sockets = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # Listening Port # tied to local address, port number 9999# 127.0.0.1 is a special IP address that represents a native address, and if bound to this address, the client must be running at the same time in order to connect, that is, the external computer cannot connect. S.bind (' 127.0.0.1 ', 9999) # Call the Listen () method to start listening on the port, the incoming parameter specifies the maximum number of waiting connections: S.listen (5) print (' Waiting for Connection ... ') # The server program accepts a connection from the client via a permanent Loop # accept () Waits and returns a socket and client IP address that indicates the client connection: import Threadingimport timedef tcplink (sock, addr) : Print (' Accept new connection from%s ... '% addr) sock.send (b ' welcome! ') While true:data = Sock.recv (1024x768) time.sleep (1) If not data or Data.decode (' utf-8 ') = = ' exit ': Break Sock.send (' Hello,%s! '% data.decode (' Utf-8 ')). Encode (' Utf-8 ')) Sock.close () print (' Connection f Rom%s closed. '% addr) while True: # accepts a new connection: sock, addr = s.accept () # Create a new thread to handle the TCP connection: T = Threading. Thread (Target=tcplink, args= (sock, addr)) T.start ()
Client
import sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 建立连接:s.connect(('127.0.0.1', 9999))# 接收欢迎消息:print(s.recv(1024).decode('utf-8'))for data in [b'Chang', b'KangKang', b'Wangbin']: # 发送数据: s.send(data) print(s.recv(1024).decode('utf-8'))s.send(b'exit')s.close()
Python Learning Network programming.py