问题描述
- 安卓 Socket通信,Socket连接不上,程序就在真机崩溃但在模拟器上正常
-
class ReceiveData extends Thread
{
int i=1;
private void reconnect( )
{
Log.i("第"+i+"次连接","reconnect刚开始执行");try { Log.i("第"+i+"次连接","Socket之前"); Socket s=new Socket("192.168.0.103",40011); Log.i("第"+i+"次连接","Socket之后"); InputStream ins=s.getInputStream(); Log.i("第"+i+"次连接","InputStream之后"); BufferedReader br=new BufferedReader(new InputStreamReader(ins)); String data=null; Log.i("第"+i+"次连接","br之后"); i++; while((data=br.readLine())!=null) { String[] datas=data.split(","); Log.i("第"+i+"次连接","datas之后"); int dianping=Integer.parseInt(datas[0]); int zhiliang=Integer.parseInt(datas[1]); float jueduijiaodu=Float.parseFloat(datas[2]); float xiangduijiaodu=Float.parseFloat(datas[3]); // hcs.refresh(dianping,zhiliang); vcs.refresh(dianping,zhiliang ); disks.refresh(xiangduijiaodu, jueduijiaodu, dianping, zhiliang); cuslinear.refresh(jueduijiaodu, xiangduijiaodu, dianping, zhiliang); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.i("第"+i+"次连接","可能没连接上"); reconnect(); } catch(Exception e) { e.printStackTrace(); } } public void run() { reconnect(); } }
在客户端的一个Activity中,启动以上线程用来接收数据,当IP地址不对时,当然也就连通不了,于是抛出异常,再重新reconnect( ) (应该没有什么问题吧?),但是在真机上反复出现几次
1: http://www.eoeandroid.com/data/attachment/forum/201403/28/141758f958x35x1733zhqp.jpg 后(大约7、8秒钟的时间,而且不会其他那几条的输出,这个我懂,因为socket没建成,于是try语句块中Socket s=new Socket("192.168.0.103",40011)后的语句就不会再执行了),该Activity就会崩溃,返回到上一个Activity,而且貌似说有内存溢出问题
而在模拟器上却不会出现这个问题。如果IP地址正确,连通了,能够正常接收数据了,也不会出现这个问题。这到底是怎么回事呢?
解决方案
是不是太占用资源了?
时间: 2024-12-30 23:00:40