python server端socket代码
时间: 2023-10-28 19:04:48 浏览: 86
py代码-socket-服务器端
很好,您可以在Python中使用socket模块来创建服务器端socket代码。以下是一个简单的示例:
```python
import socket
HOST = '127.0.0.1' # Server IP address
PORT = 8080 # Server port
BUFFER_SIZE = 1024 # Buffer size
# Create a new socket object and bind it to the host and port.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((HOST, PORT))
# Listen for incoming connections.
server_socket.listen()
print(f"Server is listening on {HOST}:{PORT}")
# Accept new connections.
while True:
client_socket, address = server_socket.accept()
print(f"Connection from {address[0]}:{address[1]} has been established.")
# Receive data from the client.
data = client_socket.recv(BUFFER_SIZE)
# Send a response back to the client.
response = "Hello, client!"
client_socket.sendall(response.encode())
# Close the connection with the client.
client_socket.close()
```
在上面的代码中,我们创建了一个socket对象并将其绑定到IP地址和端口号。然后,我们使用listen()方法开始监听传入的连接请求。在while循环中,我们使用accept()方法接受新的连接,并使用recv()方法从客户端接收数据。最后,我们使用sendall()方法将响应消息发送回客户端,并使用close()方法关闭与客户端的连接。
阅读全文