Home >Backend Development >Python Tutorial >python socket completes simple communication
python tutorialThe column introduces the socket communication method
Recommended (free): python tutorial
Introduction to socket
socket is also known as " Socket", the socket will send data through the udp/tcp protocol to achieve simple communication between two machines.
Note: If you want to use socket to achieve simple communication between two machines, please first ensure that the two machines are connected to the same local network. Of course, socket can also realize communication between a machine. You only need to set the connection object IP to 127.0.0.1, which is the local IP.
Examples
Only some practical functions are shown here.
Description | |
---|---|
Create a socket | |
Bind to an ip and port, pass in Parameters are tuples | |
Accept data | |
Send data | |
Close the socket | |
Connect to an ip and port | |
Enable listening mode on the tcp port | |
Blocking, waiting for connection |
import socket server = socket.socket()server.bind(('0.0.0.0',80))server.listen()sock,addr = server.accept()data = ""while True: tmp_data = sock.recv(1024) if tmp_data: data += tmp_data.decode("utf8") else: breakprint('%s发送的内容:%s'%(addr[0],data))sock.close()
Here we create a socket and bind it to 0.0. At the address of 0.0:80, this address can also be changed to the name of our local machine. Then we start listening mode. After the user connects, we start receiving data (note: utf8 decoding is required before accepting data).
import socket client = socket.socket()client.connect(('127.0.0.1',80))client.send("Hello,Server.".encode("utf8"))client.close()
Here we will only talk about the following two functions: connect and send. We passed in a tuple to the connect function, but of course a list will also work. The first element needs to be the connected object IP, and the second is the port. After the connection is completed, we use the send function to send the message. Before sending, we need to encode the content into utf8 type.
Send data to a websiteWe create a file called socket_website.py and enter the following code:
import socket s.connect(('www.baidu.com',443))s.send('HELLO'.encode('utf8'))s.close()
Here, we sent data to baidu.com. Since Baidu uses https protocol, we use port 443. If the code does not report an error, it means the sending was successful. At this time, Baidu's database will have an additional text content data called HELLO.
tip: If you continuously use socket to send data to a website or machine, too much data will cause the target database/machine memory to become full, leading to a crash. This implements a simple legendary ddos attackThe above is the detailed content of python socket completes simple communication. For more information, please follow other related articles on the PHP Chinese website!