Jur*_*uba 1 java sockets android tcp
所以,我一直在创建一个利用蓝牙和WiFi(用户决定)的无线鼠标应用程序,我最近决定从UDP连接到TCP连接,因为我注意到其中一个主流鼠标应用程序使用TCP而不是UDP.
我的问题:我通过TCP-IP将多个字节数组发送到我的服务器端,但感觉好像存在延迟,有没有什么方法可以加快我接收字节数组的速度?
服务器代码涉及接收:
Socket client = null;
BufferedInputStream bis = null;
try {
client = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
try {
bis = new BufferedInputStream(client.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
byte data[] = new byte[2];
if (bis != null) {
try {
while(alive && (bis.read(data)) != -1) {
System.out.println(data[0] + " " + data[1]);
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int)b.getX();
int y = (int)b.getY();
dx = data[0];
dy = data[1];
newX = x + dx;
newY = y + dy;
if(dx == -98 && dy == -98) {
// Right click
r.mousePress(InputEvent.BUTTON3_DOWN_MASK);
r.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
} else if (dx == -99 && dy == -99) {
// Left click
r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} else if (dx == -97 && dy == -97) {
// Middle click
r.mousePress(InputEvent.BUTTON2_DOWN_MASK);
r.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
Main.wifiDisconnect.doClick();
} else {
if (!recieve && (dx != 0 || dy != 0)) { // No current thread and non empty values - Start a new one
newX = x + dx;
newY = y + dy;
i = 0;
recieve = true;
mmThread = new Thread(new Runnable() {
@Override
public void run() {
while (recieve){
r.mouseMove(newX + i * dx, newY + i * dy);
r.delay(8);
i++;
}
}
});
mmThread.start();
} else if (recieve && dx == 0 && dy == 0) {
recieve = false;
try {
mmThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mmThread = null;
} else {
newX = x + dx;
newY = y + dy;
i = 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
涉及发送的客户端代码(Android):
public class sendTask extends AsyncTask<Byte, Void, Void> {
@Override
protected Void doInBackground(Byte ...bytes) {
try {
byte x = bytes[0].byteValue();
byte y = bytes[1].byteValue();
System.out.println("Message sending: " + x + " " + y);
byte buf[] = {x, y};
bos.write(buf); //buffered output stream
bos.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
591 次 |
| 最近记录: |