利用python socket+tkinter构建简陋聊天窗口
时间: 2023-10-10 10:15:08 浏览: 215
python socket实现简单聊天室及p2p聊天功能
好的,以下是一个简单的聊天窗口示例代码:
服务端代码:
```python
import socket
import threading
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg = conn.recv(1024).decode()
if msg == "quit":
connected = False
print(f"[{addr}] {msg}")
conn.send("Message received".encode())
conn.close()
def start_server():
HOST = '127.0.0.1'
PORT = 5555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print(f"[LISTENING] Server is listening on {HOST}:{PORT}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
start_server()
```
客户端代码:
```python
import socket
import tkinter as tk
def send_message(event=None):
msg = my_msg.get()
my_msg.set("")
msg_list.insert(tk.END, f"You: {msg}")
client_socket.send(msg.encode())
if msg == "quit":
client_socket.close()
top.quit()
def receive_message():
while True:
try:
msg = client_socket.recv(1024).decode()
msg_list.insert(tk.END, f"Server: {msg}")
except OSError:
break
HOST = '127.0.0.1'
PORT = 5555
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
top = tk.Tk()
top.title("Chat Room")
message_frame = tk.Frame(top)
my_msg = tk.StringVar()
my_msg.set("")
scrollbar = tk.Scrollbar(message_frame)
msg_list = tk.Listbox(message_frame, height=15, width=50, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
msg_list.pack(side=tk.LEFT, fill=tk.BOTH)
msg_list.pack()
message_frame.pack()
entry_field = tk.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send_message)
entry_field.pack()
send_button = tk.Button(top, text="Send", command=send_message)
send_button.pack()
receive_thread = threading.Thread(target=receive_message)
receive_thread.start()
tk.mainloop()
```
运行服务端和客户端代码后,就可以在聊天窗口中进行简单的文字聊天了。请注意,这个示例只是一个基础的版本,还有很多需要完善的地方,例如异常处理、多用户连接等等。
阅读全文