導航:首頁 > 操作系統 > android中socket通信

android中socket通信

發布時間:2024-09-04 22:52:58

㈠ 關於android Socket 新手求教!

1.1什麼是Socket Socket
是一種抽象層,應用程序通過它來發送和接收數據,使用Socket可以將應用程序添加到網路中,與處於同一網路中的其他應用程序進行通信。簡單來說,Socket提供了程序內部與外界通信的埠並為通信雙方的提供了數據傳輸通道。

1.2Socket的分類
根據不同的的底層協議,Socket的實現是多樣化的。本指南中只介紹TCP/IP協議族的內容,在這個協議族當中主要的Socket類型為流套接字(streamsocket)和數據報套接字(datagramsocket)。流套接字將TCP作為其端對端協議,提供了一個可信賴的位元組流服務。數據報套接字使用UDP協議,提供數據打包發送服務。
下面,我們來認識一下這兩種Socket類型的基本實現模型。

二、Socket 基本通信模型

詳細

㈡ 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();
}

㈢ android做客戶端socket如何讓點擊按鈕向伺服器發送信息

使用基於TCP協議的Socket
一個客戶端要發起一次通信,首先必須知道運行伺服器端的主機IP地址。然後由網路基礎設施利用目標地址,將客戶端發送的信息傳遞到正確的主機上,在java中,地址可以由一個字元串來定義,這個字元串可以使數字型的地址(比如192.168.1.1),也可以是主機名(example.com)。
而在android 4.0 之後系統以後就禁止在主線程中進行網路訪問了,原因是:

主線程是負責UI的響應,如果在主線程進行網路訪問,超過5秒的話就會引發強制關閉,所以這種耗時的操作不能放在主線程里。放在子線程里,而子線程里是不能對主線程的UI進行改變的,因此就引出了Handler,主線程里定義Handler,子線程里使用。
以下是一個android socket客戶端的例子:
---------------------------------Java代碼---------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TCPSocketActivity extends Activity {

public static final String TAG = TCPSocketActivity.class.getSimpleName();

/* 伺服器地址 */
private String host_ip = null;
/* 伺服器埠 */
private int host_port = 0;

private Button btnConnect;
private Button btnSend;
private EditText editSend;
private EditText hostIP;
private EditText hostPort;
private Socket socket;
private PrintStream output;
private String buffer = "";
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_test);
context = this;
initView();

btnConnect.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
host_ip = hostIP.getText().toString();
host_port = Integer.parseInt(hostPort.getText().toString());
new Thread(new ConnectThread()).start();
}
});

btnSend.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new SendThread(editSend.getText().toString())).start();
}
});
}

private void toastText(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

public void handleException(Exception e, String prefix) {
e.printStackTrace();
toastText(prefix + e.toString());
}

public void initView() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
editSend = (EditText) findViewById(R.id.sendMsg);
hostIP = (EditText) findViewById(R.id.hostIP);
hostPort = (EditText) findViewById(R.id.hostPort);
}

private void closeSocket() {
try {
output.close();
socket.close();
} catch (IOException e) {
handleException(e, "close exception: ");
}
}

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (0x123 == msg.what) {
toastText("連接成功!");
}
}
};

/* 連接socket線程 */
public class ConnectThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
if (null == socket || socket.isClosed()) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
output = new PrintStream(socket.getOutputStream(), true,
"utf-8");
}
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/*發送信息線程*/
public class SendThread implements Runnable {

String msg;

public SendThread(String msg) {
super();
this.msg = msg;
}

@Override
public void run() {
// TODO Auto-generated method stub
try {
output.print(msg);
} catch (Exception e) {
e.printStackTrace();
}
closeSocket();
}

}

public class SocketThread implements Runnable {
public String txt1;

public SocketThread(String txt1) {
super();
this.txt1 = txt1;
}

@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
/* 連接伺服器 並設置連接超時為5秒 */
if (socket.isClosed() || null == socket) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
}
// 獲取輸入輸出流
PrintStream ou = new PrintStream(socket.getOutputStream(),
true, "UTF-8");
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 讀取發來伺服器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}

// 向伺服器發送信息
ou.print(txt1);
ou.flush();
// 關閉各種輸入輸出流
bff.close();
ou.close();
socket.close();
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
}
-----------------------------布局文件activity_socket_test.xml--------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical" >

<EditText
android:id="@+id/hostIP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="伺服器ip"
android:singleLine="true"
android:inputType="text" />

<EditText
android:id="@+id/hostPort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="埠"
android:singleLine="true"
android:inputType="number" />

<Button
android:id="@+id/btnConnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/style_btn_shape"
android:layout_margin="5dip"
android:text="@string/connect"
android:textColor="@color/white" />

<EditText
android:id="@+id/sendMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="需要發送的內容"
android:inputType="text" />

<Button
android:id="@+id/btnSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:background="@drawable/style_btn_shape"
android:layout_gravity="center_vertical|center_horizontal"
android:text="@string/send"
android:textColor="@color/white" />

</LinearLayout>
-------------------------樣式文件style_btn_shape.xml----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充的顏色 -->
<solid android:color="#0465b2" />
<!-- 設置按鈕的四個角為弧形 -->
<!-- android:radius 弧形的半徑 -->
<corners android:radius="15dip" />

<!-- padding:Button裡面的文字與Button邊界的間隔 -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"
/>
</shape>
------------------------------END---------------------------------------

閱讀全文

與android中socket通信相關的資料

熱點內容
平板電腦加密失敗後玩不了 瀏覽:710
狂人c程序員入門必備 瀏覽:705
台灣伺服器域名是什麼雲空間 瀏覽:901
單片機程序電子版 瀏覽:599
路由器加密模式只有wpa2 瀏覽:530
ug刪除加密 瀏覽:433
安卓手機如何下載最低版本的抖音 瀏覽:778
sprint演算法 瀏覽:445
數控編程學習資料 瀏覽:177
pdf語文 瀏覽:943
單片機小學比賽 瀏覽:95
條件預編譯多條件 瀏覽:394
物理學好可以當程序員嗎 瀏覽:435
jsp圖片網站源碼 瀏覽:845
美股開盤加密貨幣大跌 瀏覽:18
ubuntuphp伺服器 瀏覽:189
伺服器編輯器如何寫 瀏覽:384
我有一套源碼自帶採集 瀏覽:112
對稱加密演算法的特點 瀏覽:47
河池看房用什麼app 瀏覽:283