用python写一个有UI界面,在局域网内的服务端与客户端
时间: 2023-01-11 15:55:36 浏览: 377
可以使用 Python 中的 tkinter 模块来创建 UI 界面。在服务端上,可以使用 sockets 模块来实现网络通信。下面是一个简单的例子:
```python
import socket
from tkinter import *
def on_send():
message = entry.get()
sock.sendall(message.encode())
entry.delete(0, END)
def receive():
while True:
data = sock.recv(1024)
text.insert(END, data.decode())
text.see(END)
root = Tk()
root.title("Server")
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
entry = Entry(frame)
entry.pack()
send_button = Button(frame, text="Send", command=on_send)
send_button.pack()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("0.0.0.0", 12345))
sock.listen(1)
print("Waiting for a connection...")
conn, addr = sock.accept()
print("Connection from", addr)
receive_thread = Thread(target=receive)
receive_thread.start()
root.mainloop()
```
客户端代码如下:
```python
import socket
from tkinter import *
def on_send():
message = entry.get()
sock.sendall(message.encode())
entry.delete(0, END)
def receive():
while True:
data = sock.recv(1024)
text.insert(END, data.decode())
text.see(END)
root = Tk()
root.title("Client")
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
entry = Entry(frame)
entry.pack()
send_button = Button(frame, text="Send", command=on_send)
send_button.pack()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("IP_ADDRESS", 12345))
receive_thread = Thread(target=receive)
receive_thread.start()
root.mainloop()
```
上述代码将创建一个带有文本框和发送按钮的 GUI,并在本地的 12345 端口上进行监听,客户端连接的 IP_ADDRESS 为服务器 IP地址,可以在同
阅读全文