0

我不想从服务器返回无限循环中的值,而是想创建一个方法,例如 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])

在此处输入图像描述

4

2 回答 2

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 函数中创建方法,以在发生故障时重新建立套接字连接。

于 2012-10-04T08:40:51.487 回答
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]

我不确定我的问题是否正确,但......

于 2012-10-04T09:37:46.140 回答