socket通信android
1. android上的socket通信的開源框架有哪些
xmpp協議的即時通訊方案,openfireandroidpn,等等。它們都是使用了apachemina開發,但是這些東西基本都需要二次改造開發。而且改動還很大,我也看過這些東西的源碼,發現代碼結構不太理想,耦合的情況太多,實在不好擴展。所謂XMPP協議。只不過是別人使用mina自定義了一個消息編碼解碼協議。通俗的講就是,xml形式消息的編碼與解碼,我們完全沒有必要在國外這套不成熟的openfire與xmpp上耗費過多的精力去研究,我們完全可以通過apachemina自定義自己的通訊協議,並可以為它使用自己的名字。我們不要盲目崇拜國外的有些東西,自己掌握原理,才是最重要的,各位切記~這套IM系統為我個人自主開發使用了apachemina,主要功能為服務端和客戶端,客戶端到客戶端的即時通信,可以支持包括文字圖片,語音等任何消息形式服務端使用的struts2+spring3和apacheminaandroid端也使用的apachemina。這套IM系統結構還是非常清晰合理的,非常容易擴展和改造,下面是android版本的demo的目的是只是一個演示,可以參照它的代碼,使用這套系統開發自己的東西,核心價值是一套高靈活性,相對標准化的即時通訊解決方案,即時聊天只是它的一種運用途徑!
2. Android Socket通信如何設置超時時間
今天太閑了,實在是一個寫博客的好日子! 其實關於這個問題可能用到的人不會很多,不過我在這里還是說說。 正常很多人寫socket通信時,都會直接通過new socket(IP,PORT)直接去鏈接伺服器。其實這種做法也沒有錯誤,但是若當伺服器IP不存在會伺服器沒有響應時,程序會卡在這句代碼老長一段時間,才會跳出並報異常。這對於這種問題,通過設置連接超時時間可以進行解決: socket = new Socket(); SocketAddresssocAddress = new InetSocketAddress(this.netAdress, this.port); 5000就是你所設置的超時時間!
3. android 與 服務端的 socket通信問題
登錄成功跳轉頁面 輸入查詢條件顯示結果 不需要用到socket啊
socket屬於直連接 當及時性要求高的時候才會用比如即時聊天
你的這個功能用get或者post的請求伺服器就可以了
如果你要用socket寫的化 並且多個activity用到
那麼就就把socket的連接和循環讀取並解析數據的代碼放到一個靜態類里
第一次調用連接 後面調用就無需再走連接代碼
把每一次收到服務端信息的時候加一個interface作為回調分配個相應地頁面就好了
4. 請問下,android能不能直接通過手機IP進行socket通信,不是局域.
可以的,只要通信的IP是通的就行了。
有兩種方案:
1、在PC機上建立伺服器,手機與手機之間的通信通過伺服器進行中轉
2、一部手機作為伺服器,另一部手機作為客戶端接入該手機
一般是第一種方案
1、pc端:
serverSocket=new ServerSocket(5648); //在5648埠進行偵聽
Socket sk = serverSocket.accept();//如果有接入,則創建對應的socket;
2、手機端:
socket=new Socket("tobacco5648.xicp.net",5648);//連接socket
3、消息輸入輸出:
pw=new PrintWriter(socket.getOutputStream()); //消息輸出
pw.println("發送消息");
pw.flush();
br=new BufferedReader(new InputStreamReader(socket.getInputStream())); //消息接收
while((str=br.readLine())!=null){
//接收消息
}
5. 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去啟動的話,頁面會卡住。。。
6. Android socket通信協議的封裝和解析
android socket通信協議的封裝和解析,其實是和java一樣的,都是通過http中的相關知識來封裝和解析,主要是通過多次握手,如下代碼:
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.io.PrintWriter;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
publicclassMain{
privatestaticfinalintPORT=9999;
privateList<Socket>mList=newArrayList<Socket>();
privateServerSocketserver=null;
=null;//threadpool
publicstaticvoidmain(String[]args){
newMain();
}
publicMain(){
try{
server=newServerSocket(PORT);
mExecutorService=Executors.newCachedThreadPool();//createathreadpool
System.out.println("伺服器已啟動...");
Socketclient=null;
while(true){
client=server.accept();
//把客戶端放入客戶端集合中
mList.add(client);
mExecutorService.execute(newService(client));//
}
}catch(Exceptione){
e.printStackTrace();
}
}
{
privateSocketsocket;
privateBufferedReaderin=null;
privateStringmsg="";
publicService(Socketsocket){
this.socket=socket;
try{
in=newBufferedReader(newInputStreamReader(socket.getInputStream()));
//客戶端只要一連到伺服器,便向客戶端發送下面的信息。
msg="伺服器地址:"+this.socket.getInetAddress()+"cometoal:"
+mList.size()+"(伺服器發送)";
this.sendmsg();
}catch(IOExceptione){
e.printStackTrace();
}
}
@Override
publicvoidrun(){
try{
while(true){
if((msg=in.readLine())!=null){
//當客戶端發送的信息為:exit時,關閉連接
if(msg.equals("exit")){
System.out.println("ssssssss");
mList.remove(socket);
in.close();
msg="user:"+socket.getInetAddress()
+"exittotal:"+mList.size();
socket.close();
this.sendmsg();
break;
//接收客戶端發過來的信息msg,然後發送給客戶端。
}else{
msg=socket.getInetAddress()+":"+msg+"(伺服器發送)";
this.sendmsg();
}
}
}
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*循環遍歷客戶端集合,給每個客戶端都發送信息。
*/
publicvoidsendmsg(){
System.out.println(msg);
intnum=mList.size();
for(intindex=0;index<num;index++){
SocketmSocket=mList.get(index);
PrintWriterpout=null;
try{
pout=newPrintWriter(newBufferedWriter(
newOutputStreamWriter(mSocket.getOutputStream())),true);
pout.println(msg);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
}
7. 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數據傳輸。