python简易局域网聊天工具全部代码
时间: 2024-07-17 11:01:02 浏览: 130
在Python中创建一个简易的局域网聊天工具,通常涉及到使用socket编程和多线程技术。这里是一个简化版本的示例代码,展示了如何使用TCP套接字建立一个基本的聊天服务器和客户端:
```python
# server.py (服务器端)
import socket
from threading import Thread
class Server:
def __init__(self, host='localhost', port=12345):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((host, port))
self.server.listen()
print(f"Server started on {host}:{port}")
def handle_client(self, client_socket):
request = client_socket.recv(1024).decode('utf-8')
print(f"Received message from client: {request}")
client_socket.send("You said: " + request.encode('utf-8'))
client_socket.close()
def start_server(self):
while True:
client, addr = self.server.accept()
print(f"Accepted connection from {addr}:{addr}")
client_handler = Thread(target=self.handle_client, args=(client,))
client_handler.start()
if __name__ == "__main__":
server = Server()
server.start_server()
# client.py (客户端)
import socket
def send_message(host='localhost', port=12345, message="Hello!"):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
client.send(message.encode('utf-8'))
response = client.recv(1024).decode('utf-8')
print(f"Response received: {response}")
client.close()
if __name__ == "__main__":
send_message("localhost", 12345, "Your message goes here!")
```
**相关问题--:**
1. 如何在实际环境中运行这个服务器和客户端?
2. 如果想要支持多个客户端同时连接,还需要做哪些修改?
3. 这个示例是否安全?如果需要增强安全性,应该怎么做?
阅读全文