写一个和别人聊天,收发信息的代码
时间: 2024-11-03 20:20:08 浏览: 6
编写一个简单的文本聊天程序,我们可以使用Python的socket库来模拟一个TCP客户端和服务器的通信。这里是一个基础的服务器端代码示例:
```python
import socket
# 创建一个服务器 socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 12345) # 地址和端口
server_socket.bind(server_address)
server_socket.listen(1)
print(f"Server is running on {server_address[0]}:{server_address[1]}")
while True:
# 接受连接
connection, client_address = server_socket.accept()
print(f"Accepted connection from: {client_address}")
try:
while True:
# 接收客户端的消息
received_message = connection.recv(1024).decode()
if not received_message:
break
print(f"Received: {received_message}")
# 发送回复
response = "You said: " + received_message
connection.sendall(response.encode())
except Exception as e:
print(f"Connection closed by client: {e}")
break
finally:
# 关闭连接
connection.close()
```
对于客户端,你可以创建一个新的socket,连接到指定的服务器地址,然后循环读取用户输入并发送给服务器,接收服务器的响应:
```python
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
while True:
user_input = input("Type your message and press enter: ")
client_socket.sendall(user_input.encode())
# 收到服务器响应
server_response = client_socket.recv(1024).decode()
print(f"Server responded: {server_response}")
client_socket.close()
```
这只是一个最基础的例子,实际应用中可能需要添加异常处理、身份验证等机制。
阅读全文