TCP单人聊天界面python
时间: 2024-11-28 16:15:51 浏览: 12
Tcp_Socketchat.zip
TCP(Transmission Control Protocol,传输控制协议)通常用于建立可靠的点对点连接,适合于实时通信场景,如聊天应用。要在Python中创建一个简单的TCP单人聊天界面,你可以使用socket库。下面是一个简化的示例:
```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("Server is running on port", server_address[1])
while True:
# 等待客户端连接
client_connection, client_address = server_socket.accept()
print("Accepted connection from:", client_address)
# 接收客户端消息并发送响应
while True:
data = client_connection.recv(1024) # 每次接收1k字节数据
if not data:
break
print(f"Received: {data.decode('utf-8')}")
response = "You said: " + data.decode('utf-8')
client_connection.sendall(response.encode('utf-8'))
# 关闭连接
client_connection.close()
# 关闭服务器socket
server_socket.close()
```
这个示例创建了一个监听在本地主机上某个端口的服务器,等待客户端连接。每当有客户端连接时,它会进入一个循环接收消息,并将接收到的消息显示出来,同时回复对方的信息。
阅读全文