我没有从服务器返回无限循环中的值,而是想创建一个方法,例如getPositions(),它返回连接服务器仍在运行时我想要的特定位置。我该怎么做?
import socket
import os,sys
import time
HOST = '59.191.193.59'
PORT = 5555
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST,PORT))
screen_width = 0
screen_height = 0
while True:
client_socket.send("loc\n")
data = client_socket.recv(8192)
coordinates = data.split()
if(not(coordinates[-1] == "eom" and coordinates[0] == "start")):
continue
if (screen_width != int(coordinates[2])):
screen_width = int(coordinates[2])
screen_height = int(coordinates[3])
print int(coordinates[8])
print int(coordinates[9])
print int(coordinates[12])
print int(coordinates[13])
答案 0 :(得分:0)
这应该是非常简单的:
import socket
import os,sys
import time
from threading import Thread
HOST = '59.191.193.59'
PORT = 5555
COORDINATES = []
def connect():
globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST,PORT))
def update_coordinates():
connect()
screen_width = 0
screen_height = 0
while True:
try:
client_socket.send("loc\n")
data = client_socket.recv(8192)
exept:
connect();
continue;
globals()['COORDINATES'] = data.split()
if(not(COORDINATES[-1] == "eom" and COORDINATES[0] == "start")):
continue
if (screen_width != int(COORDINATES[2])):
screen_width = int(COORDINATES[2])
screen_height = int(COORDINATES[3])
Thread(target=update_coordinates).start()
// Run your controlling app here. COORDINATES will be available in the global scope and will be updated constantly
编辑:在get_coordinates函数内创建方法,以便在发生故障时重新建立套接字连接。
答案 1 :(得分:0)
import socket
import os,sys
import time
HOST = '59.191.193.59'
PORT = 5555
# don't restrict yourself to IPv4 without any need:
client_socket = socket.create_connection((HOST,PORT))
def update_coordinates(client_socket):
client_socket.send("loc\n")
data = client_socket.recv(8192)
coordinates = data.split()
if(not(coordinates[-1] == "eom" and coordinates[0] == "start")):
return None # or so
return [int(i) for i in coordinates[1:-1]]
screen_width = 0
screen_height = 0
while True:
coord = update_coordinates(screen_width)
if coord is None: continue
# ! indexes have changed...
if (screen_width != coord[1]):
screen_width = coord[1]
screen_height = coord[2]
print coordinates[7]
print coordinates[8]
print coordinates[11]
print coordinates[12]
我不确定我的问题是否正确,但是......