python 通过socket实现在线聊天程序代码
时间: 2023-12-14 09:03:15 浏览: 86
以下是一个基本的Python在线聊天程序代码示例:
服务器代码(server.py):
```python
import socket
host = '127.0.0.1'
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print('Waiting for connection...')
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024).decode()
if not data:
break
print('Received message:', data)
message = input('Enter your message: ')
conn.sendall(message.encode())
conn.close()
```
客户端代码(client.py):
```python
import socket
host = '127.0.0.1'
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
message = input('Enter your message: ')
s.sendall(message.encode())
data = s.recv(1024).decode()
print('Received message:', data)
s.close()
```
运行服务器代码,然后运行客户端代码,就可以开始在线聊天了。注意,在运行客户端代码之前,需要先运行服务器代码。
阅读全文