7.6.4 Socket Communication Based on UDP Protocol
Category Android Basic Introduction Tutorial
Introduction:
>
This section concludes our series on Socket communication with an exploration of UDP-based Socket communication. In our first section, we have already detailed the differences between TCP and UDP. The key distinction between TCP and UDP lies in whether a connection needs to be established between the client and server before data transmission. If you have studied the first two sections on TCP, you know that data transmission involves starting the server, accepting connections, obtaining the client socket, and then performing IO operations. UDP, however, does not require this. UDP uses datagrams as the carrier for data transmission. To transmit data, you first need to define the data as a datagram, specify the destination Socket (host address and port number), and then send the data in the form of a datagram. After that, it's a wait-and-see situation; whether the server receives the data is unknown unless the server responds with a confirmation datagram. Due to time constraints, I won't be writing an Android example; instead, I'll provide Java code directly.
1. Server Implementation Steps:
>
Step 1: Create a DatagramSocket, specifying the port number
Step 2: Create a DatagramPacket
Step 3: Receive data sent by the client
Step 4: Read the data
Sample Code:
public class UPDServer {
public static void main(String[] args) throws IOException {
/*
* Receive data sent by the client
*/
// 1. Create a server-side DatagramSocket, specifying the port
DatagramSocket socket = new DatagramSocket(12345);
// 2. Create a datagram to receive data sent by the client
byte[] data = new byte[1024]; // Create a byte array to specify the size of the data packet
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3. Receive data sent by the client
System.out.println("****Server is started, waiting for client to send data");
socket.receive(packet); // This method blocks until a datagram is received
// 4. Read the data
String info = new String(data, 0, packet.getLength());
System.out.println("I am the server, the client said: " + info);
/*
* Respond to the client
*/
// 1. Define the client's address, port number, and data
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "Welcome!".getBytes();
// 2. Create a datagram containing the response data
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
// 3. Respond to the client
socket.send(packet2);
// 4. Close resources
socket.close();
}
}
2. Client Implementation Steps:
>
Step 1: Define the message to be sent
Step 2: Create a DatagramPacket containing the message to be sent
Step 3: Create a DatagramSocket
Step 4: Send the data
public class UDPClient {
public static void main(String[] args) throws IOException {
/*
* Send data to the server
*/
// 1. Define the server's address, port number, and data
InetAddress address = InetAddress.getByName("localhost");
int port = 8800;
byte[] data = "Username: admin; Password: 123".getBytes();
// 2. Create a datagram containing the data to be sent
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
// 3. Create a DatagramSocket object
DatagramSocket socket = new DatagramSocket();
// 4. Send the datagram to the server
socket.send(packet);
/*
* Receive the server's response
*/
// 1. Create a datagram to receive the server's response
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
// 2. Receive the server's response
socket.receive(packet2);
// 3. Read the data
String reply = new String(data2, 0, packet2.getLength());
System.out.println("I am the client, the server said: " + reply);
// 4. Close resources
socket.close();
}
}
Summary:
This section is relatively straightforward. It mainly involves converting data into bytes and placing them into a DatagramPacket, specifying the recipient's IP address and port number when sending. To receive, a byte array is used to buffer the data. Sending requires creating a DatagramSocket object and then calling the send method to send the datagram packet to the recipient. The code in this section is sourced from a Java Socket tutorial on Mocking. For those interested, you can check it out here: Java Socket Application - Communication Made Easy
-1.0 Android Basic Introduction Tutorial
-1.0.1 2015 Latest Android Basic Introduction Tutorial Table of Contents
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android Apps with Eclipse + ADT + SDK
-1.2.2 Developing Android Apps with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial for Basic Local Repository Operations
-1.5.2 Git: Setting Up a Remote Repository on GitHub
-1.6 How to Use the 9-Patch Image
-1.7 Interface Prototype Design
-1.8 Project Source Analysis (Various Files, Resource Access)
-1.9 Android Application Signing and Packaging
-1.11 Decompiling APK to Retrieve Code & Resources
-2.1 Concepts of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 Detailed Explanation of TextView (Text Box)
-2.3.2 Detailed Explanation of EditText (Input Box)
-2.3.3 Button (Button) and ImageButton (Image Button)
-2.3.5.RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll Bar)
- 2.4.2 Date & Time Component (Part 1)
- 2.4.3 Date & Time Component (Part 2)
- 2.4.4 Adapter Basics
- 2.4.5 Simple Usage of ListView
- 2.4.6 BaseAdapter Optimization
- 2.4.7 ListView Focus Issues
- 2.4.8 Solving Checkbox Misalignment in ListView
- 2.4.9 Data Update Issues in ListView
- 2.5.0 Building a Reusable Custom BaseAdapter
- 2.5.1 Implementing Multiple Item Layouts in ListView
- 2.5.2 Basic Usage of GridView (Grid View)
- 2.5.3 Basic Usage of Spinner (Dropdown List)
- 2.5.4 Basic Usage of AutoCompleteTextView (Auto-complete Text Field)
- 2.5.5 Basic Usage of ExpandableListView (Collapsible List)
- 2.5.6 Basic Usage of ViewFlipper (Flip View)
- 2.5.7 Basic Usage of Toast (Popup Message)
- 2.5.8 Detailed Explanation of Notification (Status Bar Notification)
- 2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
- 2.6.0 Basic Usage of Other Common Dialogs
- 2.6.1 Basic Usage of PopupWindow (Floating Box)
- 2.6.2 Menu (Menu)
- 2.6.3 Simple Usage of ViewPager
- 2.6.4 Simple Usage of DrawerLayout (Official Side Slider Menu)
- 3.1.1 Event Handling Mechanism Based on Listeners
- 3.2 Event Handling Mechanism Based on Callbacks
- 3.3 Analysis of Handler Message Passing Mechanism
- 3.4 TouchListener vs OnTouchEvent + Multi-touch
- 3.5 Listening to Content Changes in EditText
- 3.6 Responding to System Setting Events (Configuration Class)
- 3.7 AsyncTask Asynchronous Task
- 3.8 Gestures (Gestures)
- 4.1.1 Introduction to Activity
- 4.1.2 Getting Started with Activity
- 4.1.3 Advanced Activity
- 4.2.1 Introduction to Service
- 4.2.2 Advanced Service
- 4.2.3 Expert Service
- 4.3.1 BroadcastReceiver Basics
- 4.3.2 Detailed BroadcastReceiver
- 4.4.1 Introduction to ContentProvider
- 4.4.2 Further Exploration of ContentProvider – Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Basic Overview of Fragment
- 5.2.1 Fragment Example Analysis – Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Analysis – Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Analysis – Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Analysis – Bottom Navigation Bar + ViewPager Page Swiping
- 5.2.5 Fragment Example Analysis – Simple Implementation of News/Shopping App List Fragment
- 6.1 Data Storage and Access – File Storage and Reading
- 6.2 Data Storage and Access – SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access – Introduction to SQLite Database
- 6.3.2 Data Storage and Access – Further Exploration of SQLite Database
- 7.1.1 Android Network Programming Overview and HTTP Protocol Study
- 7.1.2 Study of Android HTTP Request and Response Headers
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android WebService Call
- 7.5.1 Basic Usage of WebView (Web View)
- 7.5.2 Basic Interaction Between WebView and JavaScript
- 7.5.3 WebView Considerations After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Webpage Error Codes
- 7.6.1 Socket Network Basics Preparation
- 7.6.2 TCP Protocol Based Socket Communication (1)
- 7.6.3 TCP Protocol Based Socket Communication (2)
- 7.6.4 UDP Protocol Based Socket Communication
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Comprehensive Analysis of Bitmap (Bitmap) Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Practical Example of Drawing Classes
- 8.3.3 Paint API - MaskFilter (Mask)
- 8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API - ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API - ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API - ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API - PathEffect (Path Effect)
- 8.3.13 Paint API - Shader (Image Rendering)
- 8.3.14 Paint Enum/Constants and ShadowLayer Shadow Effect
- 8.3.15 Paint API - Typeface (Font Style)
- 8.3.16 Canvas API Detailed Explanation (Part 1)
- 8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods
- 8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Android Animation Collection - Frame Animation
- 8.4.2 Android Animation Collection - Tween Animation
- 8.4.3 Android Animation Collection - Property Animation - Introduction
- 8.4.4 Android Animation Collection - Property Animation - Further Insights
- 9.1 Using SoundPool to Play Sound Effects (Duang~)
- 9.2 MediaPlayer for Audio and Video Playback
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord to Record Audio
- 10.1 TelephonyManager (Telephony Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Topic (1) - Introduction
- 10.11 Sensor Topic (2) - Orientation Sensor
- 10.12 Sensor Topic (3) - Accelerometer/Gyroscope Sensor
- 10.12 Sensor Topic (4) - Understanding Other Sensors
- 10.14 Android GPS Introduction
- 11.0 "2015 Latest Android Basic Tutorial" Concludes
- 12.1 Android Practice: DrySister App (Version 1) - Project Setup and Basic Implementation
- 12.2 DrySister App (Version 1) - Parsing Backend Data
- 12.3 DrySister App (Version 1) - Image Loading Optimization (Building a Simple Image Cache Framework)
- 12.4 DrySister App (Version 1) - Adding Data Caching (Introducing SQLite)
- 12.5 DrySister App (Version 1) - Code Review, Adjustments, and Logging Class
- 12.6 DrySister App (Version 1) - Icon Creation, Obfuscation, Signing, APK Slimming, App Release