您好,登錄后才能下訂單哦!
本來(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)客戶端向服務(wù)器發(fā)送請(qǐng)求后,服務(wù)器端才能向客戶端返回?cái)?shù)據(jù)。
而Socket通信中基于TCP/IP協(xié)議的通信則是在雙方建立起連接后就可以直接進(jìn)行數(shù)據(jù)的傳輸,在連接時(shí)可實(shí)現(xiàn)信息的主動(dòng)推送,而不需要每次由客戶端想服務(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ù)端后,客戶端點(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)客戶端的請(qǐng)求
Step 3 :連接建立后,通過(guò)輸入流讀取客戶端發(fā)送的請(qǐng)求信息
Step 4 :通過(guò)輸出流向客戶端發(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()等待客戶端連接 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ā)送過(guò)來(lái)的信息" + info); } socket.shutdownInput();//關(guān)閉輸入流 socket.close(); } }
然后我們把代碼run起來(lái),控制臺(tái)會(huì)打?。?/p>
好的,接下來(lái)到Android客戶端了!
2.Socket客戶端的編寫(xiě): 客戶端要做的事有這些:
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)建客戶端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(); } }
因?yàn)锳ndroid不允許在主線程(UI線程)中做網(wǎng)絡(luò)操作,所以這里需要我們自己 另開(kāi)一個(gè)線程來(lái)連接Socket!
運(yùn)行結(jié)果:
點(diǎn)擊按鈕后,服務(wù)端控制臺(tái)打印:
3.簡(jiǎn)易聊天室
那么通過(guò)上面的案例,我們就可以做一個(gè)簡(jiǎn)單的聊天軟件,這里知道怎么實(shí)現(xiàn)的就可以了,實(shí)戰(zhàn)中我們都是采用的第三方API,比如網(wǎng)易云,我會(huì)專門(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)有新客戶端接入,將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 = "用戶:" +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 = "用戶:" + 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è)客戶端發(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();} } } } }
接著到客戶端,客戶端的難點(diǎn)在于要另外開(kāi)辟線程的問(wèn)題,因?yàn)锳ndroid不允許直接在 主線程中做網(wǎng)絡(luò)操作,而且不允許在主線程外的線程操作UI,這里的做法是自己新建 一個(gè)線程,以及通過(guò)Hanlder來(lái)更新UI,實(shí)際開(kāi)發(fā)不建議直接這樣做?。?!
布局文件: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ū)別在于是否需要客戶端與服務(wù)端建立連接后才能進(jìn)行 數(shù)據(jù)傳輸,
TCP:傳輸前先開(kāi)服務(wù)端,accept,等客戶端接入,然后獲得 客戶端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:接收客戶端發(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ù)報(bào),用于接收客戶端發(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)啟動(dòng),等待客戶端發(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ù)器,客戶端說(shuō):" + info); /* * 向客戶端響應(yīng)數(shù)據(jù) */ // 1.定義客戶端的地址、端口號(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)客戶端 socket.send(packet2); // 4.關(guān)閉資源 socket.close(); } }
2.客戶端實(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 = "用戶名: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("我是客戶端,服務(wù)器說(shuō):" + reply); // 4.關(guān)閉資源 socket.close(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。