我正在做一个需要与 TCP 套接字通信的应用程序。我设置了一个作为我的 TCP 服务器的服务和一个作为我的 TCP 客户端的活动。
我在发送消息和从服务器接收答案方面有很大的延迟,比如 10 秒或更长时间。经过几天的研究,我发现了如何在客户端请求上设置超时并且一切都开始正常工作。
所以我的问题是,是否必须为 TCP 连接设置超时,否则它不起作用或我的实现有其他问题?
这是我的客户代码:
public static void sendTCP(final InetAddress senderAddr, final String Msg, final int serverPort) {
Thread tclient = new Thread(){
public void run() {
boolean connected;
Socket socket = new Socket();
try {
Log.d("TCP", "Client: Connecting...");
socket.bind(null);
socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);
connected = true;
try {
Log.d("TCP", "Client: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(Msg);
out.close();
}
catch (Exception e) {
Log.e("TCP", "Client: Error sending.", e);
}
} catch (Exception e) {
Log.e("TCP", "Client: Error connecting.", e);
connected = false;
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
Log.d("TCP", "Client: Connection Closed.");
} catch (IOException e) {
Log.e("TCP", "Client: Error closing connection.", e);
}
}
}
}
}
};
tclient.start();
}
和服务器的:
public void onStart(Intent intent, int startid) {
t = new Thread(){
public void run() {
try {
Boolean end = false;
Log.d("TCP", "Server: Creating server.");
ServerSocket ss = new ServerSocket(TCPPORT);
while(!end) {
//Server is waiting for client here, if needed
Log.d("TCP", "Server: Waiting on packet!");
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = input.readLine();
Log.d("TCP", "Server: Message received from client: "+st);
InetAddress senderAddr = s.getInetAddress();
senderAddrString= senderAddr.getHostAddress();
myAddrString = GetLocalIpAddress();
myAddr = InetAddress.getByName(myAddrString);
if (senderAddr.equals(myAddr)) {
}
else {
//Estraggo dal pacchetto ricevuto
try {
StringTokenizer tokens = new StringTokenizer(st, "|");
flag = tokens.nextToken();
userid = tokens.nextToken();
payload = tokens.nextToken();
}
catch (Exception e) {
Log.e("TCP", "Server: Errore estrazione dati.");
}
if (flag.equals(Constants.flag_scan_answer)) {
Log.d("TCP", "Server: Flag answer");
//devo passare i dati ad un database ScanActivity
//database(senderAddrString,userid);
System.out.println("RISPOSTA RICEVUTA DAL SERVICE TCP");
System.out.println("FLAG " + flag);
System.out.println("USERID " + userid);
System.out.println("PAYLOAD " + payload);
announceReceivingPacket();
}
else {
Log.d("TCP", "Server: CASO NON PREVISTO");
}
}
s.close();
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
}