導航:首頁 > 操作系統 > androidjava通信

androidjava通信

發布時間:2022-09-27 16:14:15

① 如何干凈的實現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/Java Socket 長連接通信

import java.*; //伺服器端 public class Server { public static void main(String args[])throws Exception { String ClientMessage; String ServerMessage; ServerSocket serversocket=new ServerSocket(5557);//埠要和客戶端對應 System.out.println("正在監聽5555埠");// while(true) { Socket collection=serversocket.accept();//調用accept()函數,建立TCP連接 DataInputStream fromClient=new DataInputStream(collection.getInputStream()); DataOutputStream toClient=new DataOutputStream(collection.getOutputStream()); ClientMessage=fromClient.readUTF();//接收來自客戶端的信息 ServerMessage=ClientMessage.toUpperCase();//轉換為大寫 toClient.writeBytes(ServerMessage);//寫到伺服器端 System.out.println("成功建立TCP連接"); } } }

③ 如何干凈的實現Android/Java Socket 長連接通信

在遠標實現過:socket模擬網頁的報文連接某個網站,創建tcp的socket後,當我socket.connect後,如果在5到7秒鍾不socket.send,那麼這個鏈接就失效了。 請問如何長時間的保持這個鏈接
這是在伺服器端的設置的,客戶端沒法設置,可以發送心跳包。
socket.connect後,每3-4秒用socket.send發送一位元組數據(內容隨便),然後觀查這個連接是否保持。

lientSocket=serverSocket.accept();
OutputStream os = clientSocket.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(al);
oos.flush();
oos.close()//socket會關閉

實現:
長連接的維持,是要客戶端程序,定時向服務端程序,發送一個維持連接包的。
如果,長時間未發送維持連接包,服務端程序將斷開連接。

客戶端:
通過持有Client對象,可以隨時(使用sendObject方法)發送Object給服務端。
如果keepAliveDelay毫秒(程序中是2秒)內未發送任何數據,則,自動發送一個KeepAlive對象給服務端,
用於維持連接。
由於,我們向服務端,可以發送很多不同的對象,服務端也可以返回不同的對象。
所以,對於返回對象的處理,要編寫具體的ObjectAction實現類進行處理。
通過Client.addActionMap方法進行添加。這樣,程序會回調處理。

服務端:
由於客戶端會定時(keepAliveDelay毫秒)發送維持連接的信息過來,所以,服務端要有一個檢測機制。
即當服務端receiveTimeDelay毫秒(程序中是3秒)內未接收任何數據,則,自動斷開與客戶端的連接。
ActionMapping的原理與客戶端相似(相同)。
通過添加相應的ObjectAction實現類,可以實現不同對象的響應、應答過程。

④ JAVA服務端android客戶端如何通信

從伺服器寫一個字元串過去可以這樣:String p = "-1,2,5";
發過去以後,將字元串分隔開,String[] ss = p.split(",");
數組裡面的元素就是位置的三個坐標了。
但鑒於你可能發送多種類型的數據,你可以寫一個協議,舉例說就是,String p ="P,-1,2,5";
分隔出來以後,可以根據數組裡面的第一個值判斷是什麼類型的數據,在執行相關的操作。

⑤ 如何干凈的實現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/Java Socket 長連接通信

我們有時候有這種需求,即我們的android客戶端要始終保持與服務端的連接,當服務端有任務或消息發送到android客戶端的時候就發送,沒有任務或消息的時候不發送但要保持這個連接,一旦有任務則開發發送,而我們的android客戶端則要保持一個時刻接收任務或消息的狀態。。。這個時候我們通過socket來實現這種需求【當然你也可以採用http輪詢的方式來不斷的從客戶端個請求服務端,這樣做有一定的弊端】實現原理:1:android客戶端通過service在後台通過servreScoket不斷的accept,一旦有相應的socket到達,則啟動一個線程去處理2::在線程中處理完返回給我們android客戶端的消息或任務之後,要將這種結果表現在ui上,這個步驟方法就比較多了,例如你可以發一個廣播來通知ui,或者你可以通過一個static的handler來處理

⑦ 如何干凈的實現Android/Java Socket 長連接通信

所謂長連接,它通常包含以下幾個關鍵過程:

  1. 輪詢的建立
    建立輪詢的過程很簡單,瀏覽器發起請求後進入循環等待狀態,此時由於伺服器還未做出應答,所以HTTP也一直處於連接狀態中。
    2. 數據的推送
    在循環過程中,伺服器程序對數據變動進行監控,如發現更新,將該信息輸出給瀏覽器,隨即斷開連接,完成應答過程,實現「伺服器推」。
    3. 輪詢的終止
    輪詢可能在以下3種情況時終止:
    3.1. 有新數據推送
    當循環過程中伺服器向瀏覽器推送信息後,應該主動結束程序運行從而讓連接斷開,這樣瀏覽器才能及時收到數據。
    3.2. 沒有新數據推送
    循環不能一直持續下去,應該設定一個最長時限,避免WEB伺服器超時(Timeout),若一直沒有新信息,伺服器應主動向瀏覽器發送本次輪詢無新信息的正常響應,並斷開連接,這也被稱為「心跳」信息。
    3.3. 網路故障或異常
    由於網路故障等因素造成的請求超時或出錯也可能導致輪詢的意外中斷,此時瀏覽器將收到錯誤信息。
    4. 輪詢的重建
    瀏覽器收到回復並進行相應處理後,應馬上重新發起請求,開始一個新的輪詢周期。

客戶端代碼片段

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="author" content="hoojo & http://hoojo.cnblogs.com"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <%@ include file="/tags/jquery-lib.jsp"%> <script type="text/javascript"> $(function () { window.setInterval(function () { $.get("${pageContext.request.contextPath}/communication/user/ajax.mvc", {"timed": new Date().getTime()}, function (data) { $("#logs").append("[data: " + data + " ]<br/>"); }); }, 3000); }); </script> </head> <body> <div id="logs"></div> </body> </html>

伺服器端代碼






@RequestMapping("/ajax") public void ajax(long timed, HttpServletResponse response) throws Exception { PrintWriter writer = response.getWriter(); Random rand = new Random(); // 死循環 查詢有無數據變化 while (true) { Thread.sleep(300); // 休眠300毫秒,模擬處理業務等 int i = rand.nextInt(100); // 產生一個0-100之間的隨機數 if (i > 20 && i < 56) { // 如果隨機數在20-56之間就視為有效數據,模擬數據發生變化 long responseTime = System.currentTimeMillis(); // 返回數據信息,請求時間、返回數據時間、耗時 writer.print("result: " + i + ", response time: " + responseTime + ", request time: " + timed + ", use time: " + (responseTime - timed)); break; // 跳出循環,返回數據 } else { // 模擬沒有數據變化,將休眠 hold住連接 Thread.sleep(1300); } } }

閱讀全文

與androidjava通信相關的資料

熱點內容
如何在vps上搭建自己的代理伺服器 瀏覽:742
nginxphp埠 瀏覽:403
內臟pdf 瀏覽:150
怎麼看雲伺服器架構 瀏覽:85
我的世界國際服為什麼登不進伺服器 瀏覽:996
微盟程序員老婆 瀏覽:930
intellij創建java 瀏覽:110
java連接odbc 瀏覽:38
啟動修復無法修復電腦命令提示符 瀏覽:359
手機編程是什麼 瀏覽:98
山東移動程序員 瀏覽:163
蘇州java程序員培訓學校 瀏覽:477
單片機液晶驅動 瀏覽:854
魔拆app里能拆到什麼 瀏覽:131
新預演算法的立法理念 瀏覽:144
wdcpphp的路徑 瀏覽:134
單片機p0口電阻 瀏覽:926
瀏覽器中調簡訊文件夾 瀏覽:594
五菱宏光空調壓縮機 瀏覽:69
為什麼app佔用幾百兆 瀏覽:680