我有一个代码,可以使用套接字将预先建立的“hi”文本发送到服务器。
当您发送完文本“hi”后,客户端将关闭。
我希望客户端保持开放状态,即使在发送“hi”之后
我为什么想要这个?因为我想在 tkinter 中创建一个按钮,以便每次按下它时都会出现“hi”。但是第一次按“hi”客户端就关闭了,其他时候就无法按了。
我该怎么办?
服务器
from socket import *
import cv2
imagem = cv2.imread("foto.png")
host = gethostname()
port = 7777
print(f'HOST: {host} , PORT {port}')
serv = socket(AF_INET, SOCK_STREAM)
serv.bind((host, port))
serv.listen(5)
con, adr = serv.accept()
msg = con.recv(1024).decode()
print(msg)
if msg == "hi":
cv2.imshow("Original", imagem)
cv2.waitKey(0)
客户
from socket import *
from tkinter import *
root = Tk()
root.geometry('430x300')
host = gethostname()
port = 7777
cli = socket(AF_INET, SOCK_STREAM)
cli.connect((host, port))
def bt4():
msg = ("hi")
cli.send(msg.encode())
btn = Button(root, text='hi', width=40, height=5, bd='10', command=bt4)
btn.place(x=65, y=100)
root.mainloop()
带有按钮的 tkinter 界面,只需按一次即可发送“hi”:
我不知道我到底做了什么,但我明白了,并且我设法解决了它,一开始它有效。
插座
from socket import *
import cv2
imagem = cv2.imread("foto.png")
host = gethostname()
port = 4444
print(f'HOST: {host} , PORT {port}')
serv = socket(AF_INET, SOCK_STREAM)
serv.bind((host, port))
serv.listen(5)
while 1:
con, adr = serv.accept()
msg = con.recv(1024).decode()
print(msg)
if msg == "hi":
cv2.imshow("Original", imagem)
cv2.waitKey(0)
客户
from socket import *
from tkinter import *
root = Tk()
root.geometry('430x300')
def bt4():
host = gethostname()
port = 4444
cli = socket(AF_INET, SOCK_STREAM)
cli.connect((host, port))
msg = ("hi")
cli.send(msg.encode())
btn = Button(root, text='hi', width=40, height=5, bd='10', command=bt4)
btn.place(x=65, y=100)
root.mainloop()