使用socket模块,实现服务器和客户端进行数据交互(聊天室功能)
时间: 2024-09-13 07:16:02 浏览: 81
基于Python Tkiner、thread与socket实现的简单多人聊天室,在Python中创建TCP服务器与客户端进行通信
5星 · 资源好评率100%
使用Python的socket模块可以创建一个基本的服务器-客户端架构来进行数据交互,例如实现一个简单的文本聊天室。这里我们将展示一个基础的实现步骤:
**服务器端(server.py)**:
```python
import socket
def start_server():
server_address = ('localhost', 12345)
buffer_size = 1024
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(server_address)
s.listen(1)
conn, addr = s.accept()
print(f"Connected by {addr[0]}:{addr[1]}")
while True:
data = conn.recv(buffer_size)
if not data:
break
print(f"Received: {data.decode('utf-8')}")
conn.sendall(data)
if __name__ == "__main__":
start_server()
```
**客户端(client.py)**:
```python
import socket
def start_client(server_ip, server_port):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((server_ip, server_port))
while True:
message = input("Enter your message: ")
client.send(message.encode('utf-8'))
received_data = client.recv(1024).decode('utf-8')
print(f"You sent: {message}\nServer replied: {received_data}")
if __name__ == "__main__":
server_ip = "localhost"
server_port = 12345 # 可以根据实际情况修改
start_client(server_ip, server_port)
```
要在终端上运行,先启动服务器,然后在另一个终端启动客户端,它们之间就可以通过指定的服务器地址和端口进行通信。
阅读全文