Simple TCP server

import socket

# Create a TCP socket (listen, link socket)
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind
tcp_socket.bind(("", 9988))

# Listen, make the socket passive, the system creates a link queue
tcp_socket.listen(128)

# Take out the successfully connected client, return a new socket (service socket), user address, if there is no client connection, it will also block
new_socket, cli_addr = tcp_socket.accept()
print(cli_addr, "successful connection")

# Receive data from the client, the client does not send content, block, note, use the service socket to receive content
recv_data = new_socket.recv(1024)
print(cli_addr, " >>>>>>>> ", recv_data.decode() )

# Reply data to the other party, use a new socket
new_socket.send("ok".encode())

# Close the socket
new_socket.close()
tcp_socket.close()

Guess you like

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