用python写一个服务端tcp通信代码
时间: 2023-04-06 16:03:41 浏览: 134
我可以回答这个问题。以下是一个简单的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 Socket通信 服务端
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通信服务端和客户端代码供您参考:
服务端代码:
import socket
HOST = ''
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
while True:
client_socket, client_address = server_socket.accept()
print('Incoming connection from:', client_address)
while True:
data = client_socket.recv(1024)
if not data:
break
client_socket.sendall(data)
client_socket.close()
客户端代码:
import socket
HOST = '127.0.0.1'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
client_socket.sendall(b'Hello, server!')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.sendall(b'How are you?')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.sendall(b'Goodbye!')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.close()
请注意,以上代码仅供参考,您需要根据您的具体要求进行修改和优化。
阅读全文