如何实现android和服务器长连接
1:android客户端通过service在后台通过servreScoket不断的accept,一旦有相应的socket到达,则启动一个线程去处理
2::在线程中处理完返回给我们android客户端的消息或任务之后,要将这种结果表现在ui上,这个步骤方法就比较多了,例如你可以发一个广播来通知ui,或者你可以通过一个static的handler来处理
service中的关键代码
private void startSocketServer()
{
if (!isStarted)
{
try
{
serverSocket = new ServerSocket( 6661 );
isStarted = true;
}
catch (Exception e)
{
// TODO: handle exception
}
// 启动线程处理
AcceptThread acceptThread = new AcceptThread();
acceptThreadstart();
}
}
class AcceptThread extends Thread
{
@Override
public void run()
{
while (isStarted)
{
try
{
// 阻塞接收
Socket client = serverSocketaccept();
initClientSocket( client );
}
catch (Exception e)
{
// TODO: handle exception
}
}
superrun();
}
}
private void initClientSocket(Socket client)
{
boolean isRunnable = true;
/
重置
/
if (cInputStream != null)
{
try
{
cInputStreamclose();
cInputStream = null;
}
catch (IOException e)
{
eprintStackTrace();
}
}
if (clientSocket != null)
{
try
{
clientSocketclose();
clientSocket = null;
}
catch (Exception e)
{
// TODO: handle exception
}
}
String resultStr = "";
clientSocket = client;
try
{
cInputStream = new DataInputStream( clientSocketgetInputStream() );
if (isRunnable)
{
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = cInputStreamread()) != -1)
{
sb1append( (char) ss );
}
resultStr = sb1toString();
//发送广播
Intent intent = new Intent();
intentputExtra( "str", resultStr );
intentsetAction( "comjonereceiver" );
sendBroadcast( intent );
// Message msg = ((MainActivity)getApplicationContext())handlerobtainMessage();
// msgobj = resultStr;
// ((MainActivity)getApplicationContext())handlersendMessage( msg );
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
isRunnable = false;
eprintStackTrace();
}
}
0条评论