当前位置:首页 » 安卓系统 » androidsocket长连接

androidsocket长连接

发布时间: 2022-10-08 02:59:42

⑴ 安卓 socket链接是长连接吗

把数据传输和socket连接分开就可以了,把SOCKET传输和接收数据写到一个线程里面,这样每次发送和接收数据就都在线程里面运行了,同时socket和线程的关闭也需要单独写在一个方法里面,发生异常的时候调用关闭 查看原帖>>

⑵ 如何干净的实现Android/java Socket 长连接通信

JavaSocket通信有很多的时候需要我们不断的学习。方面效率虽然不及C与C++但它以灵活语言优势,为大家广为使用。本文就对在使用java做通信方面程序时候应改注意问题做以说明。

1.长连接、短链接只是针对客户端而言,服务器无所谓长、短;

2.无论同步或者异步通信,发送之后务必要又响应回复,确认收到,负责进行一定范围内重发,例如重发三次;

3.长连接服务器与客户端之间务必需要心跳探测,由客户端主动发起;

4.短连接服务器通用代码:

python">packagecom.biesan.sms.gate.unioncom.communication;
importcom.biesan.commons.Constants;
importcom.biesan.commons.util.CodeUtil;
importcom.biesan.sms.gate.unioncom.data.*;
importcom.biesan.sms.gate.unioncom.util.GateInfo;
importjava.net.*;
importjava.io.*;
importjava.util.*;
importorg.apache.log4j.*;
importspApi.*;
{
//stopflag
privatebooleanunInterrupt=true;
privatebooleanunErr=true;
//privatebooleancloseSocketFlag=false;
//serversocket
privateServerSocketserverSo=null;
//currentsocket
privateSocketso=null
privateOutputStreamoutput=null;
privateInputStreaminput=null;
//gatecommand
privateSGIP_CommandtmpCmd=null;
privateSGIP_Commandcmd=null;
privateBindbind=null;
privateBindRespbindResp=null;
//privateUnbinnBind=null;
privateUnbindRespunBindResp=null;
=true;
LoggerunioncomLog=Logger.getLogger(Unioncom
Deliver.class.getName());
publicUnioncomDeliver(){
}
publicvoidrun(){
unioncomLog.info("Start...");
while(unInterrupt){
this.initServer();
this.startServices();
while(this.unAcceptErrorFlag){
try{
//接受连接请求
unioncomLog.info("beforeacceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("afteracceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
while(unErr){
cmd=newCommand();
unioncomLog.info("beforereadcommandfromstream
...........FreeMemroy:"+Runtime.getRuntime().
freeMemory());
tmpCmd=cmd.read(input);
unioncomLog.info("afterreadcommandfromstream"+
getCommandString(cmd.getCommandID())+"FreeMemroy:"+
Runtime.getRuntime().freeMemory());
if(tmpCmd==null){
unErr=false;
break;
}
switch(cmd.getCommandID()){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
this.dealBind();
break;
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
this.dealUnBind();
unioncomLog.info("afterunbindconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
break;
}//deliver
....
default://错误的命令字
break;
}//switch
}//while(unErr)
}catch(Exceptione){
unioncomLog.error("UnioncomRecvServiceError"
+e.getMessage());
}finally{
if(this.so!=null){
this.closeSocket();
}
this.unErr=true;
}
}//while(this.unAcceptErrorFlag)
try{
this.closeServerSocket();
sleep(200);//sleep
}catch(InterruptedExceptionie){
}
}//while(unInterrupt)
}
privateStringgetCommandString(intcmd){
switch(cmd){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
return"BINDCOMMAND";
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
return"UNBINDCOMMAND";
}//deliver
case...
default:
return"UNKNOWNCOMMAND";
}
}
privatevoiddealBind(){
try{
bind=newBind(tmpCmd);
if(bind.readbody()!=0){
unioncomLog.warn("ReadBinderror");
this.unErr=false;
}
bindResp=newBindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bindsuccess!");
}catch(Exceptione){
unioncomLog.error("DelaUnionRecvBindError!"+
e.getMessage());
this.unErr=false;
}
}
privatevoiddealUnBind(){
try{
//unBind=(Unbind)tmpCmd;
unBindResp=newUnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBindsuccess!");
}catch(Exceptione){
unioncomLog.warn("Unbinderror!"+e.getMessage());
}
this.unErr=false;
}
privatevoidstartServices(){
booleanunStartServices=true;
while(unStartServices){
try{
serverSo=newServerSocket(ugInfo.getLocalServerPort(),5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices=false;
unioncomLog.info("CreateunionrecvsocketOk!");
}catch(IOExceptione){
unioncomLog.warn("Createunionrecvsocketerror!"
+e.getMessage());
unStartServices=true;
UnioncomSubmit.thrSlp(3000);
}
}
}
privatevoidacceptConnection(){
//Accept失败
try{
so=serverSo.accept();
so.setSoTimeout(10000);
}catch(Exceptione){
unioncomLog.warn("AcceptError!"+e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
//Accept成功
try{
input=so.getInputStream();
output=so.getOutputStream();
}catch(IOExceptione){
unioncomLog.warn("GetI/OstreamError!"+e.getMessage());
this.closeService();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
}
privatevoidcloseSocket(){
try{
so.close();
unioncomLog.info("SocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog.error("SocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseServerSocket(){
try{
serverSo.close();
unioncomLog.info("ServerSocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog
.error("ServerSocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseService(){
this.closeSocket();
this.closeServerSocket();
}
privatevoidinitServer(){
this.bind=null;
this.bindResp=null;
//this.unBind=null;
this.unBindResp=null;
this.tmpCmd=null;
this.cmd=null;
this.serverSo=null;
this.so=null;
this.output=null;
this.input=null;
this.unErr=true;
//this.closeSocketFlag=false;
unioncomLog.info("Memory***==="
+java.lang.Runtime.getRuntime().freeMemory());
}
(){
this.unInterrupt=false;
unioncomLog.info("Requreinterrupt!!!");
}

(intmsgCoding,byte[]msgContent){
StringdeliverContent=null;
try{
if(msgContent!=null){
if(msgCoding==8){//处理ucs32编码
deliverContent=newString(msgContent,
"UnicodeBigUnmarked");
}elseif(msgCoding==0){//处理ASCII编码
deliverContent=newString(msgContent,"ASCII");
}elseif(msgCoding==4){//处理binary编码
deliverContent=newString(msgContent);
}elseif(msgCoding==15){//处理GBK编码
deliverContent=newString(msgContent,"GBK");
//处理DELIVER数据包的短信息ID
}else{
unioncomLog.error("编码格式错误!");
return"";
}
}else
return"";
returndeliverContent;
}catch(){
unioncomLog.error("dealcontenterror!"+
ex.getMessage());
return"";
}
}
}

⑶ android中怎样维护socket长连接

Service中再创建一个子线程然后一个死循环 来保持长链接

⑷ 如何在android客户端实时监控websocket长连接时服务器实时推送的

使用Socket类中的Poll方法,就可以。 Socket client //假如已经创建好了,连接到服务器端得Socket的客户端对象。 我们只要client.Poll(10,SelectMode.SelectRead)判断就行了。只要返回True是。就可以认为客户端已经断开了。 Poll 方法将会检查 Socket 的状态。指定 selectMode 参数的 SelectMode..::.SelectRead,可确定 Socket 是否为可读。指定 SelectMode..::.SelectWrite,可确定 Socket 是否为可写。使用 SelectMode..::.SelectError 检测错误条件。Poll 将在指定的时段(以 microseconds 为单位)内阻止执行。如果希望无限期的等待响应,则将 microSeconds 设置为一个负整数。如果要检查多个套接字的状态,则不妨使用 Select 方法。

⑸ 如何实现android和服务器长连接

前言:现在的大多数移动端应用都有实时得到消息的能力,简单来说,有发送消息的主动权和接受消息的被动权。例如:微信,QQ,天气预报等等,相信好处和用户体验相信大家都知道吧。

提出问题:这种功能必须涉及client(客户端)和server(服务器),所以到底client如何和server实现实时连接通讯?

分析问题:这种功能实际上就是数据同步,同时要考虑手机本身、电量、网络流量等等限制因素,所以通常在移动端上有一下两个解决方案:
1.一种是定时去server查询数据,通常是使用HTTP协议来访问web服务器,称Polling(轮询);
2.还有一种是移动端和服务器建立长连接,使用XMPP长连接,称Push(推送)。

从耗费的电量、流量和数据延迟性各方面来说,Push有明显的优势。但是使用Push的缺点是:
对于客户端:实现和维护相对成本高,在移动无线网络下维护长连接,相对有一些技术上的开发难度。
对于服务器:如何实现多核并发,cpu作业调度,数量庞大的长连接并发维护等技术,仍存在开发难点。转载,仅供参考。

⑹ 如何干净的实现Android/Java Socket 长连接通信

Java Socket通信有很多的时候需要我们不断的学习。方面效率虽然不及C与C++但它以灵活语言优势,为大家广为使用。 本文就对在使用java做通信方面程序时候应改注意问题做以说明。1.长连接、短链接只是针对客户端而言,服务器无所谓长、短;2.无论同步或者异步通信,发送之后务必要又响应回复,确认收到,负责进行一定范围内重发,例如重发三次;3.长连接服务器与客户端之间务必需要心跳探测,由客户端主动发起;4.短连接服务器通用代码:
package com.biesan.sms.gate.unioncom.communication;
import com.biesan.commons.Constants;
import com.biesan.commons.util.CodeUtil;
import com.biesan.sms.gate.unioncom.data.*;
import com.biesan.sms.gate.unioncom.util.GateInfo;
import java.net.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
import spApi.*;
public class UnioncomDeliver extends Thread {
// stop flag
private boolean unInterrupt = true;
private boolean unErr = true;
//private boolean closeSocketFlag = false;
// server socket
private ServerSocket serverSo = null;
// current socket
private Socket so = null
private OutputStream output = null;
private InputStream input = null;
// gate command
private SGIP_Command tmpCmd = null;
private SGIP_Command cmd = null;
private Bind bind = null;
private BindResp bindResp = null;
//private Unbind unBind = null;
private UnbindResp unBindResp = null;
private boolean unAcceptErrorFlag = true;
Logger unioncomLog = Logger.getLogger(Unioncom
Deliver.class.getName());
public UnioncomDeliver() {
}
public void run() {
unioncomLog.info("Start...");
while (unInterrupt) {
this.initServer();
this.startServices();
while (this.unAcceptErrorFlag) {
try {
//接受连接请求
unioncomLog.info("before accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("after accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
while (unErr) {
cmd = new Command();
unioncomLog.info("before read command from stream
........... FreeMemroy: " + Runtime.getRuntime().
freeMemory());
tmpCmd = cmd.read(input);
unioncomLog.info("after read command from stream " +
getCommandString(cmd.getCommandID()) + " FreeMemroy: " +
Runtime.getRuntime().freeMemory());
if (tmpCmd == null) {
unErr = false;
break;
}
switch (cmd.getCommandID()) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
this.dealBind();
break;
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
this.dealUnBind();
unioncomLog.info("after unbind connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
break;
}// deliver
....
default : //错误的命令字
break;
}// switch
}// while(unErr)
} catch (Exception e) {
unioncomLog.error("Unioncom Recv Service Error"
+ e.getMessage());
} finally {
if (this.so != null) {
this.closeSocket();
}
this.unErr = true;
}
}// while (this.unAcceptErrorFlag)
try {
this.closeServerSocket();
sleep(200);// sleep
} catch (InterruptedException ie) {
}
}// while(unInterrupt)
}
private String getCommandString(int cmd){
switch (cmd) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
return " BIND COMMAND ";
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
return " UNBIND COMMAND ";
}// deliver
case ...
default:
return " UNKNOWN COMMAND";
}
}
private void dealBind() {
try {
bind = new Bind(tmpCmd);
if (bind.readbody() != 0) {
unioncomLog.warn("Read Bind error");
this.unErr = false;
}
bindResp = new BindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bind success!");
} catch (Exception e) {
unioncomLog.error("Dela Union Recv Bind Error!" +
e.getMessage());
this.unErr = false;
}
}
private void dealUnBind() {
try {
//unBind = (Unbind) tmpCmd;
unBindResp = new UnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBind success!");
} catch (Exception e) {
unioncomLog.warn("Unbind error!" + e.getMessage());
}
this.unErr = false;
}
private void startServices() {
boolean unStartServices = true;
while (unStartServices) {
try {
serverSo = new ServerSocket(ugInfo.getLocalServerPort(), 5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices = false;
unioncomLog.info("Create union recv socket Ok!");
} catch (IOException e) {
unioncomLog.warn("Create union recv socket error!"
+ e.getMessage());
unStartServices = true;
UnioncomSubmit.thrSlp(3000);
}
}
}
private void acceptConnection() {
// Accept 失败
try {
so = serverSo.accept();
so.setSoTimeout(10000);
} catch (Exception e) {
unioncomLog.warn("Accept Error!" + e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
// Accept成功
try {
input = so.getInputStream();
output = so.getOutputStream();
} catch (IOException e) {
unioncomLog.warn("Get I/O stream Error!" + e.getMessage());
this.closeService();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
}
private void closeSocket() {
try {
so.close();
unioncomLog.info("Socket Close Success!!!");
} catch (Exception e) {
unioncomLog.error("Socket Close Failure!!!" + e.getMessage());
}
}
private void closeServerSocket() {
try {
serverSo.close();
unioncomLog.info("ServerSocket Close Success!!!");
} catch (Exception e) {
unioncomLog
.error("ServerSocket Close Failure!!!" + e.getMessage());
}
}
private void closeService() {
this.closeSocket();
this.closeServerSocket();
}
private void initServer() {
this.bind = null;
this.bindResp = null;
//this.unBind = null;
this.unBindResp = null;
this.tmpCmd = null;
this.cmd = null;
this.serverSo = null;
this.so = null;
this.output = null;
this.input = null;
this.unErr = true;
//this.closeSocketFlag = false;
unioncomLog.info("Memory***==="
+ java.lang.Runtime.getRuntime().freeMemory());
}
public synchronized void requireStop() {
this.unInterrupt = false;
unioncomLog.info("Requre interrupt!!!");
}
public String convertMsgContentCoding
(int msgCoding, byte[] msgContent) {
String deliverContent = null;
try {
if (msgContent != null) {
if (msgCoding == 8) { // 处理ucs32编码
deliverContent = new String(msgContent,
"UnicodeBigUnmarked");
} else if (msgCoding == 0) { // 处理ASCII编码
deliverContent = new String(msgContent, "ASCII");
} else if (msgCoding == 4) { // 处理binary编码
deliverContent = new String(msgContent);
} else if (msgCoding == 15) { // 处理GBK编码
deliverContent = new String(msgContent, "GBK");
// 处理DELIVER数据包的短信息ID
} else {
unioncomLog.error("编码格式错误!");
return "";
}
} else
return "";
return deliverContent;
} catch (UnsupportedEncodingException ex) {
unioncomLog.error("deal content error!" +
ex.getMessage());
return "";
}
}
}

⑺ android 客户端怎么实现长连接和短连接



所谓长连接,指在一个连接上可以连续发送多个数据包,然后断开连接,在连接保持期间,如果没有数据包发送,需要双方发链路检测包。短连接是指通讯双方有数据交互时,就建立一个连接,数据发送完成后,则断开此连接,即每次连接只完成一项业务的发送.

⑻ android socket 长连接,如何保存连接对象

把数据传输和socket连接分开就可以了,把SOCKET传输和接收数据写到一个线程里面,这样每次发送和接收数据就都在线程里面运行了,同时socket和线程的关闭也需要单独写在一个方法里面,发生异常的时候调用关闭 查看原帖>>

热点内容
贵州银行卡查询密码是什么 发布:2024-05-02 17:47:17 浏览:119
飓风算法没用 发布:2024-05-02 17:41:41 浏览:349
android铃声设置 发布:2024-05-02 17:40:01 浏览:484
php日记本 发布:2024-05-02 17:28:22 浏览:850
msc拒绝访问 发布:2024-05-02 17:19:09 浏览:122
php函数漏洞 发布:2024-05-02 17:15:26 浏览:963
linux访问localhost 发布:2024-05-02 17:04:11 浏览:880
剑三自动任务脚本 发布:2024-05-02 16:59:42 浏览:526
哪里有java视频教程 发布:2024-05-02 16:59:31 浏览:346
零食盒子密码多少 发布:2024-05-02 16:52:24 浏览:354