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

2.Socket通信模型:

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

好的,接下來到Android客戶端了!
2.Socket客戶端的編寫: 客戶端要做的事有這些:
Step 1 :創(chuàng)建Socket對象,指明需要鏈接的服務(wù)器的地址和端號
Step 2 :鏈接建立后,通過輸出流向服務(wù)器發(fā)送請求信息
Step 3 :通過輸出流獲取服務(wù)器響應(yīng)的信息
Step 4 :關(guān)閉相關(guān)資源
代碼實現(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)建客戶端Socket,指定服務(wù)器地址和端口
Socket socket = new Socket("172.16.2.54", 12345);
//2.獲取輸出流,向服務(wù)器端發(fā)送信息
OutputStream os = socket.getOutputStream();//字節(jié)輸出流
PrintWriter pw = new PrintWriter(os);//將輸出流包裝為打印流
//獲取客戶端的IP地址
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
pw.write("客戶端:~" + ip + "~ 接入服務(wù)器??!");
pw.flush();
socket.shutdownOutput();//關(guān)閉輸出流
socket.close();
}
}
因為Android不允許在主線程(UI線程)中做網(wǎng)絡(luò)操作,所以這里需要我們自己 另開一個線程來連接Socket!
運行結(jié)果:
點擊按鈕后,服務(wù)端控制臺打?。?/p>

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

接著把我們的程序分別跑到兩臺模擬器上:

接下來我們來寫代碼:
首先是服務(wù)端,就是將讀寫socket的操作放到自定義線程當中,創(chuàng)建ServerSocket后,循環(huán) 調(diào)用accept方法,當有新客戶端接入,將socket加入集合當中,同時在線程池新建一個線程!
另外,在讀取信息的方法中,對輸入字符串進行判斷,如果為bye字符串,將socket從集合中 移除,然后close掉!
public class Server {
//定義相關(guān)的參數(shù),端口,存儲Socket連接的集合,ServerSocket對象
//以及線程池
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ù)端運行中...\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 = "用戶:" +this.socket.getInetAddress() + "~加入了聊天室"
+"當前在線人數(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 = "用戶:" + socket.getInetAddress()
+ "退出:" +"當前在線人數(shù):"+mList.size();
socket.close();
this.sendmsg();
break;
}else{
msg = socket.getInetAddress() + " 說: " + msg;
this.sendmsg();
}
}
}
}catch(Exception e){e.printStackTrace();}
}
//為連接上服務(wù)端的每個客戶端發(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();}
}
}
}
}
接著到客戶端,客戶端的難點在于要另外開辟線程的問題,因為Android不允許直接在 主線程中做網(wǎng)絡(luò)操作,而且不允許在主線程外的線程操作UI,這里的做法是自己新建 一個線程,以及通過Hanlder來更新UI,實際開發(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="小豬簡易聊天室" /> <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;
//定義一個handler對象,用來刷新界面
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);
//當程序一開始運行的時候就實例化Socket對象,與服務(wù)端進行連接,獲取輸入輸出流
//因為4.0以后不能再主線程中進行網(wǎng)絡(luò)操作,所以需要另外開辟一個線程
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è)置點擊事件
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();
}
//重寫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ū)別在于是否需要客戶端與服務(wù)端建立連接后才能進行 數(shù)據(jù)傳輸,
TCP:傳輸前先開服務(wù)端,accept,等客戶端接入,然后獲得 客戶端socket然后進行IO操作,而UDP則不用
UDP:以數(shù)據(jù)報作為數(shù)據(jù)的傳輸載體,在進行傳輸時 首先要把傳輸?shù)臄?shù)據(jù)定義成數(shù)據(jù)報(Datagram),在數(shù)據(jù)報中指明數(shù)據(jù)要到達的Socket(主機地址 和端口號),然后再將數(shù)據(jù)以數(shù)據(jù)報的形式發(fā)送出去
1.服務(wù)端實現(xiàn)步驟:
Step 1:創(chuàng)建DatagramSocket,指定端口號
Step 2:創(chuàng)建DatagramPacket
Step 3:接收客戶端發(fā)送的數(shù)據(jù)信息
Step 4:讀取數(shù)據(jù)
示例代碼:
public class UPDServer {
public static void main(String[] args) throws IOException {
/*
* 接收客戶端發(fā)送的數(shù)據(jù)
*/
// 1.創(chuàng)建服務(wù)器端DatagramSocket,指定端口
DatagramSocket socket = new DatagramSocket(12345);
// 2.創(chuàng)建數(shù)據(jù)報,用于接收客戶端發(fā)送的數(shù)據(jù)
byte[] data = new byte[1024];// 創(chuàng)建字節(jié)數(shù)組,指定接收的數(shù)據(jù)包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3.接收客戶端發(fā)送的數(shù)據(jù)
System.out.println("****服務(wù)器端已經(jīng)啟動,等待客戶端發(fā)送數(shù)據(jù)");
socket.receive(packet);// 此方法在接收到數(shù)據(jù)報之前會一直阻塞
// 4.讀取數(shù)據(jù)
String info = new String(data, 0, packet.getLength());
System.out.println("我是服務(wù)器,客戶端說:" + info);
/*
* 向客戶端響應(yīng)數(shù)據(jù)
*/
// 1.定義客戶端的地址、端口號、數(shù)據(jù)
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "歡迎您!".getBytes();
// 2.創(chuàng)建數(shù)據(jù)報,包含響應(yīng)的數(shù)據(jù)信息
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
// 3.響應(yīng)客戶端
socket.send(packet2);
// 4.關(guān)閉資源
socket.close();
}
}
2.客戶端實現(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ù)器的地址、端口號、數(shù)據(jù)
InetAddress address = InetAddress.getByName("localhost");
int port = 8800;
byte[] data = "用戶名:admin;密碼:123".getBytes();
// 2.創(chuàng)建數(shù)據(jù)報,包含發(fā)送的數(shù)據(jù)信息
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
// 3.創(chuàng)建DatagramSocket對象
DatagramSocket socket = new DatagramSocket();
// 4.向服務(wù)器端發(fā)送數(shù)據(jù)報
socket.send(packet);
/*
* 接收服務(wù)器端響應(yīng)的數(shù)據(jù)
*/
// 1.創(chuàng)建數(shù)據(jù)報,用于接收服務(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("我是客戶端,服務(wù)器說:" + reply);
// 4.關(guān)閉資源
socket.close();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android Socket通信詳解
- Android編程之客戶端通過socket與服務(wù)器通信的方法
- Android中Socket通信的實現(xiàn)方法概述
- python服務(wù)器與android客戶端socket通信實例
- android利用websocket協(xié)議與服務(wù)器通信
- Android中使用socket通信實現(xiàn)消息推送的方法詳解
- Android Socket通信實現(xiàn)簡單聊天室
- Android中socket通信的簡單實現(xiàn)
- Android開發(fā)中Socket通信的基本實現(xiàn)方法講解
- Android Socket通信的簡單實現(xiàn)
相關(guān)文章
Android 安全加密:消息摘要Message Digest詳解
本文主要介紹Android安全加密消息摘要Message Digest,這里整理了詳細的資料,并說明如何使用Message Digest 和使用注意事項,有需要的小伙伴可以參考下2016-09-09
Android RecyclerView實現(xiàn)滑動刪除
這篇文章主要為大家詳細介紹了Android RecyclerView實現(xiàn)滑動刪除,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-07-07
Android 兩個Service的相互監(jiān)視實現(xiàn)代碼
這篇文章主要介紹了Android 兩個Service的相互監(jiān)視實現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2016-10-10
快速解決android webview https圖片不顯示的問題
今天小編就為大家分享一篇快速解決android webview https圖片不顯示的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Android中GridView和ArrayAdapter用法實例分析
這篇文章主要介紹了Android中GridView和ArrayAdapter用法,結(jié)合實例形式分析了Android中GridView結(jié)合ArrayAdapter實現(xiàn)表格化排版的相關(guān)技巧,需要的朋友可以參考下2016-02-02

