用Python写一个TCP Socket通信 服务端
时间: 2024-06-06 08:08:35 浏览: 119
import socket
HOST = '127.0.0.1' # 本地主机IP
PORT = 8000 # 监听的端口号
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建socket对象
server_socket.bind((HOST, PORT)) # 绑定端口号
server_socket.listen(1) # 监听端口,最大连接数为1
print('Server started listening on {}:{}'.format(HOST, PORT))
while True:
client_socket, address = server_socket.accept() # 接受客户端连接请求
print('Connected by', address)
data = client_socket.recv(1024).decode() # 接收客户端发送的数据
print('Received message:', data)
response = 'Hello, client! I have received your message: {}'.format(data)
client_socket.sendall(response.encode()) # 发送响应数据给客户端
client_socket.close() # 关闭客户端连接
相关问题
用python写一个服务端tcp通信代码
我可以回答这个问题。以下是一个简单的Python TCP服务器代码示例:
```python
import socket
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
# 监听客户端连接
server_socket.listen(5)
print('服务器已启动,等待客户端连接...')
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
# 接收客户端数据
data = client_socket.recv(1024)
# 处理客户端请求
response = 'Hello, ' + data.decode()
# 发送响应数据给客户端
client_socket.send(response.encode())
# 关闭客户端连接
client_socket.close()
```
这个代码创建了一个TCP服务器,绑定在本地IP地址127.0.0.1和端口号8888上。当有客户端连接时,服务器会接收客户端发送的数据,并返回一个简单的响应。
用python写一个tcp服务端
以下是一个简单的TCP服务器示例:
```
import socket
# 创建一个TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 开始监听连接请求
server_socket.listen(1)
print('Server is listening on {}:{}'.format(*server_address))
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('Received connection from {}:{}'.format(*client_address))
try:
# 接收客户端发送的数据
data = client_socket.recv(1024)
print('Received data from client: {}'.format(data))
# 向客户端发送响应
response = b'Hello, client!'
client_socket.sendall(response)
except Exception as e:
print('Error occurred while processing client request: ', e)
finally:
# 关闭客户端连接
client_socket.close()
```
此示例监听端口8888,接受客户端连接并返回“Hello, client!”响应。注意,此示例仅用于演示目的,实际服务器需要更复杂的逻辑来处理客户端请求。
阅读全文