您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Android中如何使用UDP協議傳輸數據,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
1.使用UDP協議傳輸數據
UDP協議不可靠,數據包發送出去之后無法確定是否被接收方接收到
在Java里寫好Server如下
package com.umgsai.server; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Calendar; import java.util.Date; public class Server { static Date date ; public static void main(String[] args) { while (true) { try { // 創建一個DatagramSocket對象,并指定監聽的端口號 DatagramSocket socket = new DatagramSocket(4572); byte data[] = new byte[1024]; // 創建一個空的DatagramPacket對象 DatagramPacket packet = new DatagramPacket(data, data.length); // 使用receive方法接收客戶端所發送的數據 socket.receive(packet); String result = new String(packet.getData(), packet.getOffset(), packet.getLength()); date = Calendar.getInstance().getTime(); System.out.println(date); System.out.println("result--->" + result); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
客戶端在Android里面編寫
界面activity_main.xml
<Button android:id="@+id/sendMessage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="發送消息" />
Android4.0+操作系統中連接網絡的操作不能在主線程中進行
public class MainActivity extends Activity { private Button sendMessage = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendMessage = (Button) findViewById(R.id.sendMessage); sendMessage.setOnClickListener(new clientListener()); } class clientListener implements OnClickListener{ @Override public void onClick(View v) { HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); ClientHandler clientHandler = new ClientHandler(handlerThread.getLooper()); Message msg = clientHandler.obtainMessage(); Bundle bundle = new Bundle(); msg.setData(bundle); // 將msg發送到目標對象,即生成msg對象的Handler對象 msg.sendToTarget(); } } class ClientHandler extends Handler { public ClientHandler() { } public ClientHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); try { // 首先創建一個DatagramSocket對象 DatagramSocket socket = new DatagramSocket(4572); // 創建一個InetAddree InetAddress serverAddress = InetAddress.getByName("192.168.77.215"); String str = "hello"; byte data[] = str.getBytes(); // 創建一個DatagramPacket對象,并指定要講這個數據包發送到網絡當中的哪個地址,以及端口號 DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 4572); // 調用socket對象的send方法,發送數據 socket.send(packet); socket.close(); Toast.makeText(MainActivity.this, "數據已發送", Toast.LENGTH_SHORT).show(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } }
客戶端需要的權限
<uses-permission android:name="android.permission.INTERNET" />
TCP協議是可靠的協議
TCPServer.java
public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket listen = new ServerSocket(5050); Socket server = listen.accept(); InputStream in = server.getInputStream(); OutputStream out = server.getOutputStream(); char c = (char) in.read(); System.out.println("收到:" + c); out.write('s'); out.close(); in.close(); server.close(); listen.close(); } }
TCPClient.java
public class TCPClient { public static void main(String[] args) throws IOException { Socket client = new Socket("127.0.0.1", 5050); InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream(); out.write('c'); char c = (char) in.read(); System.out.println("收到:" + c); out.close(); in.close(); client.close(); } }
Socket編程與Android操作系統無關,使用的是Java.net包里的類。
在Android里面進行網絡編程的時候要注意不能將連接網絡的代碼放到主線程里。
PS:在非UI線程里顯示Toast的時候要按照下面的方式寫
Looper.prepare(); Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); Looper.loop();
Mars視頻提供的TCP例子如下
Server端
class ServerThread extends Thread { public void run(){ //聲明一個ServerSocket對象 ServerSocket serverSocket = null; try { //創建一個ServerSocket對象,并讓這個Socket在4567端口監聽 serverSocket = new ServerSocket(4567); //調用ServerSocket的accept()方法,接受客戶端所發送的請求 Socket socket = serverSocket.accept(); //從Socket當中得到InputStream對象 InputStream inputStream = socket.getInputStream(); byte buffer [] = new byte[1024*4]; int temp = 0; //從InputStream當中讀取客戶端所發送的數據 while((temp = inputStream.read(buffer)) != -1){ System.out.println(new String(buffer,0,temp)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Client端
public class TCPClient { public static void main(String[] args) { try { //創建一個Socket對象,指定服務器端的IP地址和端口號 Socket socket = new Socket("192.168.1.104",4567); //使用InputStream讀取硬盤上的文件 InputStream inputStream = new FileInputStream("f://file/words.txt"); //從Socket當中得到OutputStream OutputStream outputStream = socket.getOutputStream(); byte buffer [] = new byte[4*1024]; int temp = 0 ; //將InputStream當中的數據取出,并寫入到OutputStream當中 while((temp = inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, temp); } outputStream.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
在調試的時候拋如下異常,暫未解決
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at com.umgsai.server.TCPServer.main(TCPServer.java:25)
關于“Android中如何使用UDP協議傳輸數據”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。