程序不断地从发送方接收数据。当我检查它时,我有一个选中/未选中按钮,它运行 if
部分……这很好。现在我把它取消选中else
部分运行和打印 Unchecked going to close socket
, 但是 s.shutdown(10)
& s.close()
不关闭套接字它显示 错误 s.shutdown(10) 不是套接字对象 OS [Errno 10022] 提供了无效参数 为什么它不关闭套接字或有其他方法可以关闭它。
附加要求
如果我的套接字再次关闭,我想让它检查(第二次)以运行 if
再次从发送方计算机接收数据的部分是否可以在不关闭我的程序的情况下再次启动套接字。
def show_markers(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname('192.168.225.12')
s.connect((host, port))
scale=0
while True:
if self.iconAction.isChecked():
print ('Checked')
m = QgsVertexMarker(self.iface.mapCanvas())
data = s.recv(SIZE)
data1 = s.recv(SIZE)
c = data.decode()
d = data1.decode()
x = float(c)
y = float(d)
print("printing X :", x)
print("printing Y :", y)
rect = QgsRectangle(float(x)-scale, float(y)-scale, float(x)+scale, float(y)+scale)
me = self.iface.mapCanvas()
me.setExtent(rect)
me.refresh()
m.setCenter(QgsPointXY(x, y))
m.setColor(QColor(255, 0, 0))
m.setIconSize(7)
m.setIconType(QgsVertexMarker.ICON_X) # or ICON_CROSS, ICON_X
m.setPenWidth(3)
else:
print('Unchecked going to close socket')
s.shutdown(10)
s.close()
我假设它应该像这样工作:最佳答案
一旦一个套接字被关闭或关闭,你就不能恢复它,而必须创建一个新的。
总体设计应该是:
def show_markers(self):
scale=0
active_socket = False
while True:
if self.iconAction.isChecked():
print ('Checked')
if not active_socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname('192.168.225.12')
s.connect((host, port))
active_socket = True
...
else:
if active_socket:
print('Unchecked going to close socket')
s.shutdown(10) # ??
s.close()
active_socket = False
我已经标记了
shutdown
行审问,因为我不明白你在这里想做什么。首先出于便携性原因,您应该 从不使用数值,但只能使用 socket
提供的常量模块。下一个 shutdown
很少在 graceful shutdown 之外使用这里没有完全实现。
关于python - 带有 if 循环的套接字不会给出一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071572/