當前位置:首頁 » 安卓系統 » 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和線程的關閉也需要單獨寫在一個方法裡面,發生異常的時候調用關閉 查看原帖>>

熱點內容
我的世界正版好玩的pvp伺服器 發布:2024-04-19 16:28:38 瀏覽:17
光遇安卓渠道服怎麼更換實名認證 發布:2024-04-19 16:18:08 瀏覽:263
關閉ip訪問 發布:2024-04-19 15:59:18 瀏覽:730
大屏安卓系統哪個好 發布:2024-04-19 15:49:10 瀏覽:792
解壓瀏覽器 發布:2024-04-19 15:39:22 瀏覽:575
pythonutfgbk 發布:2024-04-19 15:32:20 瀏覽:221
騰訊雲伺服器搭建網站打不開 發布:2024-04-19 15:32:15 瀏覽:967
光遇腳本輔助下載免費ios 發布:2024-04-19 15:22:11 瀏覽:243
表格VB腳本 發布:2024-04-19 15:13:07 瀏覽:780
python生成器表達式 發布:2024-04-19 15:12:10 瀏覽:747