'How to leave a socket client always open working, even after sending the text, please?
I have a code that sends a pre-established "hi" text to a server using socket.
1- When you finish sending the text "hi", the client closes.
2-I would like the client to remain open, even after sending the "hi"
3- Why do I want this? Because I want to create a button in tkinter, so that every time I press it, the "hi" appears. But the first time I press "hi", the client closes, and it is not possible to press other times.
What do I do please???
Server
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)
Client
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()
The tkinter interface with the button, it is possible to press only once to send a "hi":
Solution 1:[1]
I don't know exactly what I did, but I understood, and I managed to solve it, at first it worked, Thank you! In case anyone has the same question
Socket
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)
Client
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Julia |

