用python语言实现基于C/S模式的简单聊天程序
时间: 2024-05-12 16:19:56 浏览: 56
基于C/S模式的聊天程序
客户端代码:
```python
import socket
host = '127.0.0.1'
port = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
while True:
message = input("你:")
client_socket.send(message.encode('utf-8'))
data = client_socket.recv(1024).decode('utf-8')
print("服务器:", data)
```
服务端代码:
```python
import socket
host = '127.0.0.1'
port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("等待客户端连接...")
conn, addr = server_socket.accept()
print("客户端已连接:", addr)
while True:
data = conn.recv(1024).decode('utf-8')
print("客户端:", data)
message = input("你:")
conn.send(message.encode('utf-8'))
```
运行服务端代码,然后运行客户端代码即可开始聊天。
阅读全文