當前位置:首頁 » 安卓系統 » androidsocket數據

androidsocket數據

發布時間: 2022-07-06 20:26:57

A. android的socket問題,一直接收不到數據,幫忙看看

while(true){}死循環了,不知道你的本意是不是想一直讀數據,然後去更新顯示?

提出建議:

  1. 把內容全部讀出來,可以使用StringBuffer或StringBuild,然後再刷新顯示

  2. Socket使用以後要記得close

B. 如何用socket實現android手機與手機之間的通信

參考一般的java的socket編程,如果通過手機網路,就不要使用UDP即可。

C. android socket有幾種方法

/***第一種:客戶端Socket通過構造方法連接伺服器***/
//客戶端Socket可以通過指定IP地址或域名兩種方式來連接伺服器端,實際最終都是通過IP地址來連接伺服器
//新建一個Socket,指定其IP地址及埠號
Socket socket = new Socket("192.168.0.7",80);
/***Socket 客戶端 一些常用設置***/
//客戶端socket在接收數據時,有兩種超時:1.連接伺服器超時,即連接超時;2.連接伺服器成功後,接收伺服器數據超時,即接收超時
//*設置socket 讀取數據流的超時時間
socket.setSoTimeout(5000);
//發送數據包,默認為false,即客戶端發送數據採用Nagle演算法
//但是對於實時交互性高的程序,建議其改為true,即關閉Nagle演算法,客戶端每發送一次數據,無論數據包大小都會將這些數據發送出去
socket.setTcpNoDelay(true);
//設置客戶端socket關閉時,close()方法起作用時延遲1分鍾關閉,如果1分鍾內盡量將未發送的數據包發送出去
socket.setSoLinger(true, 60);
//設置輸出流的發送緩沖區大小,默認是8KB,即8096位元組
socket.setSendBufferSize(8096);
//設置輸入流的接收緩沖區大小,默認是8KB,即8096位元組
socket.setReceiveBufferSize(8096);
//作用:每隔一段時間檢查伺服器是否處於活動狀態,如果伺服器端長時間沒響應,自動關閉客戶端socket
//防止伺服器端無效時,客戶端長時間處於連接狀態
socket.setKeepAlive(true);
/*** Socket客戶端向伺服器端發送數據 ****/
//客戶端向伺服器端發送數據,獲取客戶端向伺服器端輸出流
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//代表可以立即向伺服器端發送單位元組數據
socket.setOOBInline(true);
//數據不經過輸出緩沖區,立即發送
socket.sendUrgentData(65);//"A"
//向伺服器端寫數據,寫入一個緩沖區
//註:此處字元串最後必須包含「\r\n\r\n」,告訴伺服器HTTP頭已經結束,可以處理數據,否則會造成下面的讀取數據出現阻塞
//在write()方法中可以定義規則,與後台匹配來識別相應的功能,例如登錄Login()方法,可以寫為write("Login|test,123 \r\n\r\n"),供後台識別;
bw.write("Login|test,123 \r\n\r\n");
//發送緩沖區中數據,必須有
bw.flush();

/*** Socket客戶端讀取伺服器端響應數據 ****/
//socket.isConnected代表是否連接成功過
if((socket.isConnected() == true) && (socket.isClosed() == false)){//判斷Socket是否處於連接狀態
//客戶端接收伺服器端的響應,讀取伺服器端向客戶端的輸入流
InputStream is = socket.getInputStream();
//緩沖區
byte[] buffer = new byte[is.available()];
//讀取緩沖區
is.read(buffer);
//轉換為字元串
String responseInfo = new String(buffer);
//日誌中輸出
Log.i("TEST", responseInfo);
} //關閉網路
socket.close();
/***第二種:通過connect方法連接伺服器***/
Socket socket_other = new Socket();
//使用默認的連接超時
socket_other.connect(new InetSocketAddress("192.168.0.7",80));
//連接超時2s
socket_other.connect(new InetSocketAddress("192.168.0.7",80),2000);
//關閉socket
socket_other.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

D. Android socket 獲得16進制數據

mDataOutputClient = new DataOutputStream(mSocketClient.getOutputStream());
//發送
mDataOutputClient.write(0XFF);
mDataOutputClient.flush();
//接收
DataInputStream dis = new DataInputStream(mSocketClient.getInputStream());
int r=dis.readInt(); //接收int

接收十六進制。==> byte r=dis.readByte();
發送十六進制。==> byte r= (byte) 0xFF; dos.writeByte(r);

BufferedReader不推薦使用,因為不適合。

E. android socket請求數據怎麼抓包

從網路上面搜索到的資料看,要抓取手機中app的網路包有下面幾種方式:
(1).將tcpmp移植到Android平台,然後在命令行下啟動tcpmp進行抓包。Tcpmp程序實際上可以看作是wireshark的命令行版本,將該程序移植到Android平台直接抓包,這是一種最直接的抓包方式,然後將抓獲的數據包文件,從手機傳到windows系統上用wireshark打開進行分析,這種方式貌似不能用於蘋果手機。
(2).使用fiddler,在windows系統上打開fiddler軟體,該軟體會將我們的電腦變成一個代理,然後在手機上設置wifi網路,將代理指定為開啟fiddler的那台電腦,並且埠設置為fiddler偵聽的8888埠,這時候使用手機訪問的數據,就會通過該代理,在fiddler中就可以看到http的數據包。這種方法我試了半天怎麼都看不到數據包,不知道哪裡出問題了,根據原理,這種方式支持可以通過代理訪問網路的手機。所以從原理上說是支持Android和蘋果手機的。
(3).通過各種方式在pc電腦上建立wifi熱點,然後使用wireshark在pc電腦上監視該wifi熱點,通過手機連接該熱點訪問網路。這樣wireshark會獲取所有流經該熱點的數據包這種方式適用於所有能夠無線訪問的手機,也就是說所有的Android和蘋果手機。
那麼如何在pc電腦上建立wifi熱點呢,有這么幾種辦法:
(1).Win7電腦經過設置,可以將無線網卡設置為wifi熱點,這種方法我以前用過,可以成功,但是步驟繁瑣,而且不一定能夠成功,其他的windows系統估計就沒戲了。
(2).使用軟體自動建立wifi熱點,不需要自己手工配置,這樣的軟體有Connectify Hotspot,獵豹免費wifi,360免費wifi軟體,這幾個軟體我都使用過,比較好用,這種方式同樣也只能針對有無線網卡的筆記本電腦,原理也是將筆記本電腦上的無線網卡建立熱點了,只不過是軟體自動的,不需要人工設置,比方法1要方便。
注意:經過實驗發現,手機連接這種方式建立的熱點,所發送的數據,用wireshark去抓包,需要捕獲電腦上本身聯網的那個「網路連接」,例如我的筆記本上面有一個「本地連接」,該連接是使用有線網路的。我用獵豹免費wifi軟體建立一個熱點之後,我的電腦上多出一個「無線網路連接3」,可以看到該「無線網路連接3」是獵豹生成的,但是我抓包的時候,wireshark需要捕獲「本地連接」上的包,也就是我的手機訪問的數據實際上還是使用的「本地連接」,通信IP也是「本地連接」上的IP地址,而在手機的wifi連接設置中看到的ip地址,在我抓的包中也搜不到,也就是說手機通過該熱點訪問網路,實際上還是使用的「本地連接」的IP地址,至於是什麼原理,我目前也不太清楚。但是下面要說的隨身wifi硬體則與此不同,隨身wifi是建立了網卡。
(3).使用隨身wifi硬體。這種也是很方便的方法,而且比較穩定,對筆記本電腦和台式機都可以使用。我之前買了一個360的隨身wifi(不是打廣告,本人對360公司不感冒,但是他的隨身wifi做的確實還可以,同事中有買小米wifi的,不太穩定)。只要在360的官網上下載驅動,直接插上隨身wifi就可以使用,我推薦使用這種方法。
如果你用的是筆記本電腦可以使用方法2,如果是台式機器可以使用方法3。

F. android socket 接收伺服器返回數據,如何查找想要的數值

Android 客戶端代碼:

package com.ltb.SCActivity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SCActivity extends Activity {
private TextView mRecvText = null;
private EditText mSentText = null;
private Button mSendRecvButton = null;
private Socket mSocket = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mRecvText = (TextView)findViewById(R.id.recvText);
mSentText = (EditText)findViewById(R.id.sentText);
mSendRecvButton = (Button)findViewById(R.id.sendRecvButton);

mSendRecvButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String sentMessage = mSentText.getText().toString() + "\r\n";

try {
mSocket = new Socket("10.126.38.155", 12577);

Log.i("------SCActivity---before send---", sentMessage);

PrintWriter send = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())));
send.println(sentMessage);
send.flush(); //Important!!!!!!
//send.write(sentMessage);
Log.i("------SCActivity---after send---", sentMessage);

BufferedReader recv = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
Log.i("------SCActivity---Before ---recv.readLine()---", sentMessage);
String recvMsg = recv.readLine();
Log.i("------SCActivity---after ---recv.readLine()---", recvMsg);
if (recvMsg != null) {
mRecvText.setText(recvMsg);
} else {
mRecvText.setText("Cannot receive data correctly.");
}

send.close();
recv.close();
mSocket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}

伺服器端代碼:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12577);
while (true) {
Socket client = serverSocket.accept();
System.out.println("accept");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
PrintWriter pout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//pout.write("Server Received Message: " + str);
pout.println("Server Received Message: " + str);

System.out.println("after send in server");
/* BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);*/

pout.close();
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

public static void main(String argv[] ) {
Thread pcServerThread = new Thread(new Server());
pcServerThread.start();
}
}

G. android如何與手機進行通信(Socket連接)

其實跟電腦差不多了,android里調用socket的方法,拿到socket後就可以發送數據並接收數據。

我最近正在做android方面的通信,真的想把完整的代碼都給你,可是沒辦法,公司機密。。

給你我的socket連接類吧。。。

package sean.socket;

///////////把MyType的一些方法替換成Writer的方法
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import sean.Sysout;
import sean.business.BusinessCenter;
import sean.business.LoginManager;
import sean.format.MyType;
import sean.io.Reader;
import sean.transfer.BytesBuffer;
import sean.transfer.DataCenter;

public class SocketThread implements Runnable {

String Server = "";
int Port = 0;
static Socket cs = null;
// Thread ioThread=null;
static boolean bool_SocketThread = false;
static OutputStream output = null;

public SocketThread(String server, int port) {
Server = server;
Port = port;
bool_SocketThread = true;
}

@Override
public void run() {
// TODO Auto-generated method stub
while (bool_SocketThread) {
try {
// if (cs == null) {
DataCenter.setBool_Login(false);// 設置登錄失敗
Sysout.println("正在嘗試連接ClientSocket...", Sysout.TempOutDebug);
cs = new Socket(InetAddress.getByName(Server), Port);
if (cs != null) {
Sysout.println("ClientSocket連接成功!__" + cs,
Sysout.TempOutDebug);
cs.setKeepAlive(true);//讓socket保持活動狀態

InputStream input = cs.getInputStream();
output = cs.getOutputStream();
BusinessCenter.sendLoginData();

BytesBuffer bBuffer = new BytesBuffer();
byte[] Buffer = new byte[1024];
int ReadBytes = input.read(Buffer);
while (ReadBytes != -1) {
Sysout.println("已讀取" + ReadBytes + "個位元組到緩沖區",
Sysout.TempOutDebug);
byte[] b = new byte[ReadBytes];
b = MyType.BytesInsertToBytes(Buffer, b, 0);
Reader r = new Reader(b);
Sysout.println(r.toString() + "____ReadBytes=="
+ ReadBytes, Sysout.TempOutDebug);
bBuffer.InsertToBuffer(Buffer, ReadBytes);
ReadBytes = input.read(Buffer);
}
} else {
Sysout.printException("ClientSocket連接失敗!請確認網路正常且伺服器已開啟。");
}
// }
// 執行到這里說明inputstream.read()已中斷,說明socket已斷開連接
// cs=null;
LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
DataCenter.setBool_Login(false);// 數據中心登錄注銷
Sysout.printException(cs + "已斷開。");
Thread.sleep(2 * 1000);// 睡眠2秒後繼續循環

// try {
// // 判斷ClientSocket是否已斷開
// cs.sendUrgentData(0);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// Sysout.printException("ClientSocket已斷開,重新連接。"+e);
// cs.close();
// cs = null;
// }
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====解析伺服器名稱發生異常!" + e);
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread發生IO異常,異常消息:" + e);
try {
if (cs != null) {
Sysout.println("准備關閉" + cs, Sysout.TempOutDebug);
cs.shutdownOutput();
cs.shutdownInput();
cs.close();
cs = null;
output = null;
LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
DataCenter.setBool_Login(false);// 數據中心登錄注銷
Sysout.println(cs + "已關閉。", Sysout.TempOutDebug);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====線程睡眠異常!!"
+ e2);
// e2.printStackTrace();
}
String ExceptionInfos=e.toString();
if(ExceptionInfos.endsWith("Connection refused")){
stopSocketThread();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
Sysout.printException(cs + "關閉發生異常::" + e1);
// e1.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====線程睡眠異常!!"
+ e2);
// e2.printStackTrace();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// while(bool_SocketThread)
Sysout.println("SocketThread已停止。", Sysout.TempOutDebug);
}

public static Socket getSocket() {
return cs;
}

// public void setBool(boolean bool0) {
// bool_SocketThread = bool0;
// }

public static OutputStream getOutputStream() {
return output;
}

public static void stopSocketThread() {
try {
// 停止SocketThread線程,必須先把循環的標志bool_SocketThread置為false,否則可能繼續循環,重新建立socket連接
bool_SocketThread = false;
// 關閉socket
if (cs != null) {
cs.shutdownOutput();
cs.shutdownInput();
cs.close();
cs = null;
output = null;

Sysout.println("ClientSocket已被強制關閉。");
// LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
// DataCenter.setBool_Login(false);// 數據中心登錄注銷
// byte[] lock=LoginActivity.getLock();
// synchronized(lock){
// lock.notify();
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
Sysout.printException("強制關閉" + cs + "發生異常::" + e);
// e.printStackTrace();
}
}

}

必須先在android里啟動一個服務,由服務去啟動這個socket線程,因為如果是UI去啟動的話,頁面會卡住。。。

H. android socket通信

首先,你要實現的就是從資料庫里讀數據,然後通過socket傳過去。

但是明明開一個線程就行的,為什麼要開兩個線程呢。而之所以會出現這個問題就是因為再加上主線程,三個線程的變數全共享了。而線程運行本身就是宏觀上並行的,不知道三線程哪個先,哪個後,這也就是為什麼有時候有數據,有時候沒數據,完全放大的線程的不確定性。

最後線程通知UI要用Handle實現。

{
privatebooleanisConnect=true;
publicvoidrun(){
socket=newSocket(HOST,POST);
output=newPrintWriter(socket.getOutputStream(),true);
input=newBufferedReader(newInputStreamReader(socket.getInputStream(),"gbk"));
while(isConnect){
//傳回的XML字元串
xmlback=input.readLine();//無數據會阻塞
//returnxmlback;//從伺服器端返回值xmlback
用Handle傳回值給主線程,不用return.
}
}
publicStringsendMessage(SendxmlVOsend){//send應該是存值的,不看見用上,自己結合操作資料庫改一下
Stringxmlback="";
//生成xml文件轉換成字元串(xmlstring)
output.println(xmlstring+" ");
}
publicvoidclose(){
isConnect=false;
input.close();
output.close();
socket.close();
}
}

你試試這個樣子寫,

I. Android socket通信能發數據但不能接收到數據

我C#項目中做過同樣的Android移動Socket通信。

Android客戶端:

SocketClient對象receive函數就調用讀取函數,當然之前是打開了Socket連接。

publicStringreceive()throwsIOException{

BufferedReaderreader=newBufferedReader(
newInputStreamReader(client.getInputStream()));
Stringtxt=reader.readLine();

returntxt;
}

Activity頁面使用任務不間斷監聽接收。

<Void,Void,Void>{
@Override
protectedVoiddoInBackground(Void...arg0){

SocketClientclient=SocketClient.getInstance();

while(true)
{
try{
Thread.sleep(5000);

Stringre=client.receive();

if(re==null||(re!=null&&re.equals(""))){
continue;
}

if(isCancelled())
returnnull;

//TODO:處理接收到消息

}catch(SocketExceptione){
//服務端斷開,啟動重連任務
if(e.getMessage().contains("ECONNRESET")){
reconnectTask=newReconnectServerTask();
reconnectTask.execute((Void)null);
}
returnnull;
}catch(IOExceptione){
e.printStackTrace();
}catch(InterruptedExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
}
}

J. Android Socket通信開發,求詳細過程,附加註釋,謝謝

服務端往Socket的輸出流裡面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流裡面寫東西,然後服務端對應的Socket的輸入流就可以讀出對應的內容。
Socket類型為流套接字(streamsocket)和數據報套接字(datagramsocket)。
Socket基本實現原理
TCP與UDP
1基於TCP協議的Socket
伺服器端首先聲明一個ServerSocket對象並且指定埠號,然後調用Serversocket的accept()方法接收客戶端的數據。accept()方法在沒有數據進行接收的處於堵塞狀態。(Socketsocket=serversocket.accept()),一旦接收到數據,通過inputstream讀取接收的數據。
客戶端創建一個Socket對象,指定伺服器端的ip地址和埠號(Socketsocket=newSocket("172.168.10.108",8080);),通過inputstream讀取數據,獲取伺服器發出的數據(OutputStreamoutputstream=socket.getOutputStream()),最後將要發送的數據寫入到outputstream即可進行TCP協議的socket數據傳輸。

熱點內容
scratch少兒編程課程 發布:2025-04-16 17:11:44 瀏覽:627
榮耀x10從哪裡設置密碼 發布:2025-04-16 17:11:43 瀏覽:356
java從入門到精通視頻 發布:2025-04-16 17:11:43 瀏覽:73
php微信介面教程 發布:2025-04-16 17:07:30 瀏覽:297
android實現陰影 發布:2025-04-16 16:50:08 瀏覽:787
粉筆直播課緩存 發布:2025-04-16 16:31:21 瀏覽:337
機頂盒都有什麼配置 發布:2025-04-16 16:24:37 瀏覽:202
編寫手游反編譯都需要學習什麼 發布:2025-04-16 16:19:36 瀏覽:800
proteus編譯文件位置 發布:2025-04-16 16:18:44 瀏覽:356
土壓縮的本質 發布:2025-04-16 16:13:21 瀏覽:582