詳解Android 基于TCP和UDP協(xié)議的Socket通信
本來(lái)想講一下基礎(chǔ)的網(wǎng)絡(luò)通信方面的知識(shí)點(diǎn),發(fā)現(xiàn)太枯燥乏味了,不過(guò)筆試中也經(jīng)常會(huì)問(wèn)到這方面的問(wèn)題,所以關(guān)于通信方面的知識(shí)點(diǎn),小編會(huì)放到面試中去,因?yàn)閷?shí)戰(zhàn)中也就面試會(huì)用到這方面知識(shí)點(diǎn)
Android與服務(wù)器的通信方式主要有兩種,一是Http通信,一是Socket通信。兩者的最大差異在于,http連接使用的是“請(qǐng)求—響應(yīng)方式”,即在請(qǐng)求時(shí)建立連接通道,當(dāng)客戶(hù)端向服務(wù)器發(fā)送請(qǐng)求后,服務(wù)器端才能向客戶(hù)端返回?cái)?shù)據(jù)。
而Socket通信中基于TCP/IP協(xié)議的通信則是在雙方建立起連接后就可以直接進(jìn)行數(shù)據(jù)的傳輸,在連接時(shí)可實(shí)現(xiàn)信息的主動(dòng)推送,而不需要每次由客戶(hù)端想服務(wù)器發(fā)送請(qǐng)求。而UDP則是提供無(wú)連接的數(shù)據(jù)報(bào)服務(wù),UDP在發(fā)送數(shù)據(jù)報(bào)前不需建立連接,不對(duì)數(shù)據(jù)報(bào)進(jìn)行檢查即可發(fā)送數(shù)據(jù)包
1.什么是Socket?

2.Socket通信模型:

Socket通信實(shí)現(xiàn)步驟解析:
Step 1:創(chuàng)建ServerSocket和Socket
Step 2:打開(kāi)連接到的Socket的輸入/輸出流
Step 3:按照協(xié)議對(duì)Socket進(jìn)行讀/寫(xiě)操作
Step 4:關(guān)閉輸入輸出流,以及Socket
好的,我們接下來(lái)寫(xiě)一個(gè)簡(jiǎn)單的例子,開(kāi)啟服務(wù)端后,客戶(hù)端點(diǎn)擊按鈕然后鏈接服務(wù)端, 并向服務(wù)端發(fā)送一串字符串,表示通過(guò)Socket鏈接上服務(wù)器~
一、1.基于TCPSocket服務(wù)端的編寫(xiě):
服務(wù)端要做的事有這些:
Step 1 :創(chuàng)建ServerSocket對(duì)象,綁定監(jiān)聽(tīng)的端口
Step 2 :調(diào)用accept()方法監(jiān)聽(tīng)客戶(hù)端的請(qǐng)求
Step 3 :連接建立后,通過(guò)輸入流讀取客戶(hù)端發(fā)送的請(qǐng)求信息
Step 4 :通過(guò)輸出流向客戶(hù)端發(fā)送響應(yīng)信息 Step 5 :關(guān)閉相關(guān)資源
代碼實(shí)現(xiàn):
創(chuàng)建一個(gè)Java項(xiàng)目,然后把Java代碼貼進(jìn)去即可!這里可以用eclipse來(lái)寫(xiě)服務(wù)端,as來(lái)寫(xiě)安卓端
public class SocketServer {
public static void main(String[] args) throws IOException {
//1.創(chuàng)建一個(gè)服務(wù)器端Socket,即ServerSocket,指定綁定的端口,并監(jiān)聽(tīng)此端口
ServerSocket serverSocket = new ServerSocket(12345);
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
Socket socket = null;
//2.調(diào)用accept()等待客戶(hù)端連接
System.out.println("~~~服務(wù)端已就緒,等待客戶(hù)端接入~,服務(wù)端ip地址: " + ip);
socket = serverSocket.accept();
//3.連接后獲取輸入流,讀取客戶(hù)端信息
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
is = socket.getInputStream(); //獲取輸入流
isr = new InputStreamReader(is,"UTF-8");
br = new BufferedReader(isr);
String info = null;
while((info=br.readLine())!=null){//循環(huán)讀取客戶(hù)端的信息
System.out.println("客戶(hù)端發(fā)送過(guò)來(lái)的信息" + info);
}
socket.shutdownInput();//關(guān)閉輸入流
socket.close();
}
}
然后我們把代碼run起來(lái),控制臺(tái)會(huì)打?。?/p>

好的,接下來(lái)到Android客戶(hù)端了!
2.Socket客戶(hù)端的編寫(xiě): 客戶(hù)端要做的事有這些:
Step 1 :創(chuàng)建Socket對(duì)象,指明需要鏈接的服務(wù)器的地址和端號(hào)
Step 2 :鏈接建立后,通過(guò)輸出流向服務(wù)器發(fā)送請(qǐng)求信息
Step 3 :通過(guò)輸出流獲取服務(wù)器響應(yīng)的信息
Step 4 :關(guān)閉相關(guān)資源
代碼實(shí)現(xiàn):
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_accept = (Button) findViewById(R.id.btn_accept);
btn_accept.setOnClickListener(this);
}
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
try {
acceptServer();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void acceptServer() throws IOException {
//1.創(chuàng)建客戶(hù)端Socket,指定服務(wù)器地址和端口
Socket socket = new Socket("172.16.2.54", 12345);
//2.獲取輸出流,向服務(wù)器端發(fā)送信息
OutputStream os = socket.getOutputStream();//字節(jié)輸出流
PrintWriter pw = new PrintWriter(os);//將輸出流包裝為打印流
//獲取客戶(hù)端的IP地址
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
pw.write("客戶(hù)端:~" + ip + "~ 接入服務(wù)器!!");
pw.flush();
socket.shutdownOutput();//關(guān)閉輸出流
socket.close();
}
}
因?yàn)锳ndroid不允許在主線程(UI線程)中做網(wǎng)絡(luò)操作,所以這里需要我們自己 另開(kāi)一個(gè)線程來(lái)連接Socket!
運(yùn)行結(jié)果:
點(diǎn)擊按鈕后,服務(wù)端控制臺(tái)打?。?/p>

3.簡(jiǎn)易聊天室
那么通過(guò)上面的案例,我們就可以做一個(gè)簡(jiǎn)單的聊天軟件,這里知道怎么實(shí)現(xiàn)的就可以了,實(shí)戰(zhàn)中我們都是采用的第三方API,比如網(wǎng)易云,我會(huì)專(zhuān)門(mén)寫(xiě)一個(gè)網(wǎng)易云的IM通信
實(shí)現(xiàn)的效果圖:
先把我們的服務(wù)端跑起來(lái):

接著把我們的程序分別跑到兩臺(tái)模擬器上:

接下來(lái)我們來(lái)寫(xiě)代碼:
首先是服務(wù)端,就是將讀寫(xiě)socket的操作放到自定義線程當(dāng)中,創(chuàng)建ServerSocket后,循環(huán) 調(diào)用accept方法,當(dāng)有新客戶(hù)端接入,將socket加入集合當(dāng)中,同時(shí)在線程池新建一個(gè)線程!
另外,在讀取信息的方法中,對(duì)輸入字符串進(jìn)行判斷,如果為bye字符串,將socket從集合中 移除,然后close掉!
public class Server {
//定義相關(guān)的參數(shù),端口,存儲(chǔ)Socket連接的集合,ServerSocket對(duì)象
//以及線程池
private static final int PORT = 12345;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService myExecutorService = null;
public static void main(String[] args) {
new Server();
}
public Server()
{
try
{
server = new ServerSocket(PORT);
//創(chuàng)建線程池
myExecutorService = Executors.newCachedThreadPool();
System.out.println("服務(wù)端運(yùn)行中...\n");
Socket client = null;
while(true)
{
client = server.accept();
mList.add(client);
myExecutorService.execute(new Service(client));
}
}catch(Exception e){e.printStackTrace();}
}
class Service implements Runnable
{
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msg = "用戶(hù):" +this.socket.getInetAddress() + "~加入了聊天室"
+"當(dāng)前在線人數(shù):" +mList.size();
this.sendmsg();
}catch(IOException e){e.printStackTrace();}
}
@Override
public void run() {
try{
while(true)
{
if((msg = in.readLine()) != null)
{
if(msg.equals("bye"))
{
System.out.println("~~~~~~~~~~~~~");
mList.remove(socket);
in.close();
msg = "用戶(hù):" + socket.getInetAddress()
+ "退出:" +"當(dāng)前在線人數(shù):"+mList.size();
socket.close();
this.sendmsg();
break;
}else{
msg = socket.getInetAddress() + " 說(shuō): " + msg;
this.sendmsg();
}
}
}
}catch(Exception e){e.printStackTrace();}
}
//為連接上服務(wù)端的每個(gè)客戶(hù)端發(fā)送信息
public void sendmsg()
{
System.out.println(msg);
int num = mList.size();
for(int index = 0;index < num;index++)
{
Socket mSocket = mList.get(index);
PrintWriter pout = null;
try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true);
pout.println(msg);
}catch (IOException e) {e.printStackTrace();}
}
}
}
}
接著到客戶(hù)端,客戶(hù)端的難點(diǎn)在于要另外開(kāi)辟線程的問(wèn)題,因?yàn)锳ndroid不允許直接在 主線程中做網(wǎng)絡(luò)操作,而且不允許在主線程外的線程操作UI,這里的做法是自己新建 一個(gè)線程,以及通過(guò)Hanlder來(lái)更新UI,實(shí)際開(kāi)發(fā)不建議直接這樣做?。。?/p>
布局文件:activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="小豬簡(jiǎn)易聊天室" /> <TextView android:id="@+id/txtshow" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/editsend" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btnsend" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="發(fā)送" /> </LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements Runnable {
//定義相關(guān)變量,完成初始化
private TextView txtshow;
private EditText editsend;
private Button btnsend;
private static final String HOST = "172.16.2.54";
private static final int PORT = 12345;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
private StringBuilder sb = null;
//定義一個(gè)handler對(duì)象,用來(lái)刷新界面
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
sb.append(content);
txtshow.setText(sb.toString());
}
}
;
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = new StringBuilder();
txtshow = (TextView) findViewById(R.id.txtshow);
editsend = (EditText) findViewById(R.id.editsend);
btnsend = (Button) findViewById(R.id.btnsend);
//當(dāng)程序一開(kāi)始運(yùn)行的時(shí)候就實(shí)例化Socket對(duì)象,與服務(wù)端進(jìn)行連接,獲取輸入輸出流
//因?yàn)?.0以后不能再主線程中進(jìn)行網(wǎng)絡(luò)操作,所以需要另外開(kāi)辟一個(gè)線程
new Thread() {
public void run() {
try {
socket = new Socket(HOST, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//為發(fā)送按鈕設(shè)置點(diǎn)擊事件
btnsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = editsend.getText().toString();
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
}
}
}
});
new Thread(MainActivity.this).start();
}
//重寫(xiě)run方法,在該方法中輸入流的讀取
@Override
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {
if ((content = in.readLine()) != null) {
content += "\n";
handler.sendEmptyMessage(0x123);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、基于UDP協(xié)議的Socket通信
TCP和UDP最大的區(qū)別在于是否需要客戶(hù)端與服務(wù)端建立連接后才能進(jìn)行 數(shù)據(jù)傳輸,
TCP:傳輸前先開(kāi)服務(wù)端,accept,等客戶(hù)端接入,然后獲得 客戶(hù)端socket然后進(jìn)行IO操作,而UDP則不用
UDP:以數(shù)據(jù)報(bào)作為數(shù)據(jù)的傳輸載體,在進(jìn)行傳輸時(shí) 首先要把傳輸?shù)臄?shù)據(jù)定義成數(shù)據(jù)報(bào)(Datagram),在數(shù)據(jù)報(bào)中指明數(shù)據(jù)要到達(dá)的Socket(主機(jī)地址 和端口號(hào)),然后再將數(shù)據(jù)以數(shù)據(jù)報(bào)的形式發(fā)送出去
1.服務(wù)端實(shí)現(xiàn)步驟:
Step 1:創(chuàng)建DatagramSocket,指定端口號(hào)
Step 2:創(chuàng)建DatagramPacket
Step 3:接收客戶(hù)端發(fā)送的數(shù)據(jù)信息
Step 4:讀取數(shù)據(jù)
示例代碼:
public class UPDServer {
public static void main(String[] args) throws IOException {
/*
* 接收客戶(hù)端發(fā)送的數(shù)據(jù)
*/
// 1.創(chuàng)建服務(wù)器端DatagramSocket,指定端口
DatagramSocket socket = new DatagramSocket(12345);
// 2.創(chuàng)建數(shù)據(jù)報(bào),用于接收客戶(hù)端發(fā)送的數(shù)據(jù)
byte[] data = new byte[1024];// 創(chuàng)建字節(jié)數(shù)組,指定接收的數(shù)據(jù)包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3.接收客戶(hù)端發(fā)送的數(shù)據(jù)
System.out.println("****服務(wù)器端已經(jīng)啟動(dòng),等待客戶(hù)端發(fā)送數(shù)據(jù)");
socket.receive(packet);// 此方法在接收到數(shù)據(jù)報(bào)之前會(huì)一直阻塞
// 4.讀取數(shù)據(jù)
String info = new String(data, 0, packet.getLength());
System.out.println("我是服務(wù)器,客戶(hù)端說(shuō):" + info);
/*
* 向客戶(hù)端響應(yīng)數(shù)據(jù)
*/
// 1.定義客戶(hù)端的地址、端口號(hào)、數(shù)據(jù)
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "歡迎您!".getBytes();
// 2.創(chuàng)建數(shù)據(jù)報(bào),包含響應(yīng)的數(shù)據(jù)信息
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
// 3.響應(yīng)客戶(hù)端
socket.send(packet2);
// 4.關(guān)閉資源
socket.close();
}
}
2.客戶(hù)端實(shí)現(xiàn)步驟:
Step 1:定義發(fā)送信息
Step 2:創(chuàng)建DatagramPacket,包含將要發(fā)送的信息
Step 3:創(chuàng)建DatagramSocket
Step 4:發(fā)送數(shù)據(jù)
public class UDPClient {
public static void main(String[] args) throws IOException {
/*
* 向服務(wù)器端發(fā)送數(shù)據(jù)
*/
// 1.定義服務(wù)器的地址、端口號(hào)、數(shù)據(jù)
InetAddress address = InetAddress.getByName("localhost");
int port = 8800;
byte[] data = "用戶(hù)名:admin;密碼:123".getBytes();
// 2.創(chuàng)建數(shù)據(jù)報(bào),包含發(fā)送的數(shù)據(jù)信息
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
// 3.創(chuàng)建DatagramSocket對(duì)象
DatagramSocket socket = new DatagramSocket();
// 4.向服務(wù)器端發(fā)送數(shù)據(jù)報(bào)
socket.send(packet);
/*
* 接收服務(wù)器端響應(yīng)的數(shù)據(jù)
*/
// 1.創(chuàng)建數(shù)據(jù)報(bào),用于接收服務(wù)器端響應(yīng)的數(shù)據(jù)
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
// 2.接收服務(wù)器響應(yīng)的數(shù)據(jù)
socket.receive(packet2);
// 3.讀取數(shù)據(jù)
String reply = new String(data2, 0, packet2.getLength());
System.out.println("我是客戶(hù)端,服務(wù)器說(shuō):" + reply);
// 4.關(guān)閉資源
socket.close();
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android Socket通信詳解
- Android編程之客戶(hù)端通過(guò)socket與服務(wù)器通信的方法
- Android中Socket通信的實(shí)現(xiàn)方法概述
- python服務(wù)器與android客戶(hù)端socket通信實(shí)例
- android利用websocket協(xié)議與服務(wù)器通信
- Android中使用socket通信實(shí)現(xiàn)消息推送的方法詳解
- Android Socket通信實(shí)現(xiàn)簡(jiǎn)單聊天室
- Android中socket通信的簡(jiǎn)單實(shí)現(xiàn)
- Android開(kāi)發(fā)中Socket通信的基本實(shí)現(xiàn)方法講解
- Android Socket通信的簡(jiǎn)單實(shí)現(xiàn)
相關(guān)文章
Android中TextView自動(dòng)識(shí)別url且實(shí)現(xiàn)點(diǎn)擊跳轉(zhuǎn)
這篇文章主要介紹了關(guān)于Android中TextView自動(dòng)識(shí)別url且實(shí)現(xiàn)點(diǎn)擊跳轉(zhuǎn)的相關(guān)資料,文中給出了詳細(xì)的示例代碼,對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-03-03
Android開(kāi)發(fā)筆記之:Handler Runnable與Thread的區(qū)別詳解
本篇文章是對(duì)在Android中Handler Runnable與Thread的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android性能優(yōu)化之Bitmap圖片優(yōu)化詳解
在Android項(xiàng)目的imageview中使用大圖bitmap時(shí)會(huì)占據(jù)很大的內(nèi)存,而且在很多時(shí)候我們并不需要顯示原圖那么大的圖片, 所以我們需要對(duì)圖片進(jìn)行優(yōu)化,這篇文章主要介紹了Android性能優(yōu)化之Bitmap圖片優(yōu)化的相關(guān)資料,需要的朋友們下面來(lái)一起看看吧。2017-04-04
Android App打包加固后的APK無(wú)法安裝問(wèn)題解決
Android應(yīng)用當(dāng)中,很多隱私信息都是以 字符串的形式存在的,所以需要加密,本文主要介紹了Android App打包加固后的APK無(wú)法安裝問(wèn)題解決,感興趣的可以了解一下2024-01-01
Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序示例
這篇文章主要介紹了Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序,結(jié)合實(shí)例形式分析了Android藍(lán)牙程序的原理與客戶(hù)端、服務(wù)器端具體實(shí)現(xiàn)步驟,需要的朋友可以參考下2016-10-10
Compose?動(dòng)畫(huà)藝術(shù)之屬性動(dòng)畫(huà)探索
這篇文章主要介紹了Compose動(dòng)畫(huà)藝術(shù)之屬性動(dòng)畫(huà)探索,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09

