7.6.2 Socket Communication Based on TCP Protocol (1)
Category Android Basic Tutorial
Introduction to This Section:
>
Wasn't the previous concept lesson a bit dull, but there was still some gain, right? Starting from this section, let's delve into the study of Socket communication based on the TCP protocol. First, let's understand the concept of Socket, the communication model of Socket, the steps to implement Socket, and what the two parties as the Socket server and client need to do! Okay, let's delve into Socket step by step!
1. What is a Socket?
2. Socket Communication Model:
Analysis of Socket Communication Implementation Steps:
>
Step 1: Create ServerSocket and Socket
Step 2: Open the input/output streams of the connected Socket
Step 3: Perform read/write operations on the Socket according to the protocol
Step 4: Close the input/output streams and the Socket
Alright, let's write a simple example next. After starting the server, the client clicks the button and then connects to the server, sending a string to the server to indicate that it has connected to the server via Socket~
3. Writing of the Socket Server:
The things the server needs to do are as follows:
>
Step 1: Create a ServerSocket object, bind to the listening port
Step 2: Call the accept() method to listen for client requests
Step 3: After the connection is established, read the client's request information through the input stream
Step 4: Send response information to the client through the output stream
Step 5: Close related resources
Code Implementation:
Simply create a Java project in Eclipse and paste the Java code into it!
public class SocketServer {
public static void main(String[] args) throws IOException {
//1. Create a server-side Socket, i.e., ServerSocket, specify the port to bind, and listen to this port
ServerSocket serverSocket = new ServerSocket(12345);
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
Socket socket = null;
//2. Call accept() to wait for the client to connect
System.out.println("~~~Server is ready, waiting for the client to connect~, server IP address: " + ip);
socket = serverSocket.accept();
//3. After the connection, get the input stream and read the client's information
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
is = socket.getInputStream(); //Get the input stream
isr = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(isr);
String info = null;
while ((info = br.readLine()) != null) { //Loop to read the client's information
System.out.println("Information sent by the client: " + info);
}
socket.shutdownInput(); //Close the input stream
socket.close();
}
}
Then we run the code, and the console will print:
4. Writing of the Socket Client:
The things the client needs to do are as follows:
>
Step 1: Create a Socket object, specify the server's address and port number that need to be connected
Step 2: After the connection is established, send request information to the server through the output stream
Step 3: Obtain the server's response information through the output stream
Step 4: Close related resources
Code Implementation:
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. Create a client-side Socket, specify the server address and port
Socket socket = new Socket("172.16.2.54", 12345);
//2. Get the output stream and send information to the server
OutputStream os = socket.getOutputStream(); //Byte output stream
PrintWriter pw = new PrintWriter(os); //Wrap the output stream as a print stream
//Get the client's IP address
@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 = "User: " + socket.getInetAddress()
+ " exited: " + "Current online count: " + mList.size();
socket.close();
this.sendmsg();
break;
} else {
msg = socket.getInetAddress() + " says: " + msg;
this.sendmsg();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Send messages to each client connected to the server
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();}
}
}
}
Moving on to the client side, the challenge with the client is the need to create a separate thread, as Android does not allow network operations to be performed directly in the main thread, and also does not allow UI operations outside of the main thread. The approach here is to create a new thread and update the UI through a Handler. This method is not recommended for actual development!!!
Layout file: **activity_main.xml** :
```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="Simple Chat Room" />
<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="Send"
/>
</LinearLayout>
MainActivity.java:
```java public class MainActivity extends AppCompatActivity implements Runnable {
//Define related variables and initialize
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;
//Define a handler object to refresh the interface
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);
//When the program starts, instantiate the Socket object to connect with the server and obtain the input and output streams.
//Since version 4.0, network operations can no longer be performed in the main thread, so a separate thread is needed.
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();
//Set click event for the send button
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();
}
//Override the run method to read the input stream
@Override
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket
handler.sendEmptyMessage(0x123); } } } } catch (Exception e) { e.printStackTrace(); } } }
Summary of This Section:
>
Well, this section explained the TCP-based Socket communication for everyone. It introduced the model of Socket communication, implemented a simple example of Socket communication, and wrote an enhanced version example: Piggy Chat Room. I believe it will bring convenience to you who are just involved in Socket programming ~, thank you~
-1.0 Android Basic Tutorial for Beginners
-1.0.1 Latest Android Basic Tutorial Table of Contents for 2015
-1.1 Background and System Architecture Analysis
-1.2 Setting Up the Development Environment
-1.2.1 Developing Android APP with Eclipse + ADT + SDK
-1.2.2 Developing Android APP with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Installing Genymotion Emulator
-1.5.1 Git Tutorial on Basic Operations of Local Repositories
-1.5.2 Git: Using GitHub to Set Up a Remote Repository
-1.6 How to Play with the 9 (Jiu Mei) Images
-1.7 Interface Prototype Design
-1.8 Project Related Analysis (Various Files, Resource Access)
-1.9 Android Program Signing and Packaging
-1.11 Decompiling APK to Obtain Code & Resources
-2.1 The Concept 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 TextView (Text Box) Detailed Explanation
-2.3.2 EditText (Input Box) Detailed Explanation
-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 View)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.4 Basic Explanation of Adapter
-2.4.5 Simple and Practical ListView
-2.4.6 Optimization of BaseAdapter
-2.4.7 Focus Issues with ListView
-2.4.8 Solving Checkbox Misalignment Issues in ListView
-2.4.9 Data Update Issues with ListView
-2.5.0 Building a Reusable Custom BaseAdapter
-[2.5.1 Implementing Multiple Layouts for ListView
5.2.1 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 3)
6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
7.1.1 What to Learn in Android Network Programming and Study of HTTP Protocol
7.1.2 Learning about Android HTTP Request and Response Headers
7.6.2 Socket Communication Based on TCP Protocol (1)
8.3.4 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 1)
[8.3.5 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 2)](android-tutorial-xfermode-porterd
11.0 "2015 Latest Android Basic Tutorial" Completion Celebration~
12.2 DrySister Girl Viewing App (First Edition) - 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) - 4. Adding Data Caching (Integrating SQLite)