0
我已經在我的電腦上建立了一個服務器在Java中,客戶端是我的Android手機。Android的TCP套接字連接慢
我試圖模擬我的應用程序中的鼠標行爲,但問題是即使在第一分鐘一切運行順利,最後在客戶端和服務器之間有一個巨大的延遲。
Server代碼
try {
System.out.println(InetAddress.getLocalHost());
serverSocket = new ServerSocket(4444); // Server socket
serverSocket.setReceiveBufferSize(10000);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
try {
clientSocket = serverSocket.accept(); // accept the client connection
System.out.println("connection initiated");
DataInputStream din = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());
/* do my things here */
din.close();
dout.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading "+ex);
}
客戶端代碼
@Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
//Inet4Address.getLocalHost().toString(); //InetAddress.getLocalHost().getHostAddress().toString();
System.out.println(dstAddress);
socket = new Socket(dstAddress, dstPort);
socket.setSendBufferSize(10000);
DataInputStream din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF(kappa);
response = "sent to server";
String msg = din.readUTF();
response += msg;
din.close();
dout.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = e.toString();
}
return null;
}
(卡帕是一個全球性的字符串,我每一次修改。)
可能是什麼情況?
'/ *在這裏做我的事* /'。至少展示你如何閱讀和寫作。 – greenapps
爲什麼要爲每個字符串創建一個新的套接字/客戶端?爲什麼不保持連接打開? – greenapps
'(kappa是我每次修改的全局字符串)'。你每次發送多少個字符?多久? – greenapps