实时向服务器发送数据

时间:2014-03-01 19:25:54

标签: android multithreading tcp client-server

我试图为Android制作远程鼠标应用程序(通过TCP从手机控制PC上的鼠标)。在clientside(android)上,我在UIThread中实现了OnTouchListener,但客户端套接字和IO在另一个线程中运行。服务器接收坐标,但只有一次,即使客户端正在发送一段时间(真实)循环并且我将手指移动到手机的显示屏上。它应该永久发送最新的坐标,而不仅仅是第一个坐标。

public class MainActivity extends Activity implements OnTouchListener {
private ServerSocket ss;
private Socket socket;
TextView tv;
String x, y;
private static final int SERVERPORT = 444;
private static final String SERVER_IP = "192.168.1.3";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.textView1);
    RelativeLayout l = (RelativeLayout) findViewById(R.id.myView);
    l.setOnTouchListener(this);
}

class Worker implements Runnable{

    PointF point;
    public Worker(PointF point) {
        this.point = point;
    }
    @Override
    public void run() {
        try {
            InetAddress adress = InetAddress.getByName(SERVER_IP);
            socket = new Socket("192.168.1.3", SERVERPORT);
            BufferedWriter obf = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                obf.write(point.x+" "+point.y);
                obf.flush();
                obf.close();


        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
   ExecutorService executor = Executors.newFixedThreadPool(5);

@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();

    switch (action) {
    case MotionEvent.ACTION_MOVE:
        x=String.valueOf(event.getX());
        y=String.valueOf(event.getY());
        tv.setText(x+" + "+y);
        PointF point = new PointF(event.getX(), event.getY());
        executor.execute(new Worker(point));
        break;

    default:
        break;
    }
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

你可以简单地实现这个......

class Worker implements Runnable{
    PointF point;
    public Worker(PointF point) {
        this.point = point;
    }
    @Override
    public void run() {

        //send pointf to server here 
    }

}
   ExecutorService executor = Executors.newFixedThreadPool(5);

@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();

    switch (action) {
    case MotionEvent.ACTION_MOVE:

        PointF point = new PointF(event.getX(), event.getY());
        executor.execute(new Worker(point));
        break;

    default:
        break;
    }
    return true;
}