使用TCP SOCKET技术完成聊天室的功能 python 代码
时间: 2023-07-23 22:13:49 浏览: 55
以下是使用TCP SOCKET技术完成聊天室的Python代码示例:
服务器端代码:
```python
import socket
import threading
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(5)
clients = []
def handle_client(client_socket, address):
while True:
try:
message = client_socket.recv(1024)
if message:
broadcast(message, client_socket)
else:
remove(client_socket)
except:
remove(client_socket)
def broadcast(message, client_socket):
for client in clients:
if client != client_socket:
try:
client.send(message)
except:
client.close()
remove(client)
def remove(client_socket):
if client_socket in clients:
clients.remove(client_socket)
while True:
client_socket, address = server_socket.accept()
clients.append(client_socket)
print(f'Connected by {address}')
threading.Thread(target=handle_client, args=(client_socket, address)).start()
```
客户端代码:
```python
import socket
import threading
HOST = '127.0.0.1'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
def receive():
while True:
try:
message = client_socket.recv(1024)
print(message.decode('utf-8'))
except:
print('Error receiving message')
client_socket.close()
break
def send():
while True:
message = input()
client_socket.send(message.encode('utf-8'))
threading.Thread(target=receive).start()
threading.Thread(target=send).start()
```
这是一个简单的聊天室实现,可以让多个客户端连接到服务器,实现多人同时在线的聊天功能。当客户端发送消息时,服务器会将消息广播给所有客户端,实现多人同时在线的交流。需要注意的是,这个实现还有很多不足之处,需要根据具体需求进行改进。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)