我需要你的帮助。我想这样做:我的socket TCP
中有Timer
和IntentService
任务。这是我的代码:
protected void onHandleIntent(Intent intent)
{
String add = intent.getStringExtra("address");
Log.d("add",add);
int porta = Integer.parseInt(intent.getStringExtra("port"));
InetAddress serverAddr = null;
try
{
serverAddr = InetAddress.getByName(add);
socket = new Socket(serverAddr, porta);
socketHandler.setSocket(socket);
final PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.print("go");
out.flush();
final byte[] bytes = new byte[1000];
int counter;
String reader;
final InputStream data = socket.getInputStream();
int numRead = 0;
if ((numRead = data.read(bytes)) >= 0)
{
reader=new String(bytes, 0, numRead);
}
if (reader.equals("Let's go"))
{
//socket connected
}
pingTimer = new Timer();
pingTimer.scheduleAtFixedRate(new TimerTask() {
String reader; int r;
public void run()
{
out.write("ping");
out.flush();
if(out.checkError())
{
onDestroy();
}
}
}, 0, 20000);
InputStream readeIn = socket.getInputStream();
char [] buffer = new char[1024];
BufferedReader in = new BufferedReader(new InputStreamReader(readeIn));
while((counter = in.read(buffer)) != -1)
{
//read here
}
catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
onDestroy();
}
}
public void onDestroy()
{
//destroy socket
}
它运作良好。现在我想这样做:我想把一个计时器放到套接字上。所以,插座上升了3分钟;如果它收到了什么,重新放3分钟听,但如果在这3分钟套接字没有收到任何东西,我想关闭套接字。我该怎么做? 谢谢你的回答。
答案 0 :(得分:0)
您需要使用Socket.setSoTimeout()
的参数调用3*60*1000
,该参数对应于三分钟(60分钟给出秒,1000分钟给出毫秒),并相应地处理结果SocketTimeoutException