Android Network Programming and android Network Programming instances
Step 1: Implement socket communication.
First, I learned socket programming, which is the most basic.
We use the PC to write a Java program as the server, and then write an Android app as the client, and then implement communication.
Create a Java class as follows:
import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class SimpleServer { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(30000); while (true) { Socket socket = ss.accept(); OutputStream os = socket.getOutputStream(); os.write("my email is ruihanL@126.com".getBytes("utf-8")); os.close(); socket.close(); } }}
Click to run the job. In case of abnormal operation, open the task manager, stop javaw.exe, and click run again.
The andriod app code is as follows:
package com.example.simpleclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;public class MainActivity extends ActionBarActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textView1); new Thread(){ public void run(){ try{ Socket socket = new Socket("192.168.10.103",30000); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = br.readLine(); textView.setText(line); br.close(); socket.close(); } catch(IOException e) { e.printStackTrace(); } } }.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}
Change the IP address to the IP address of the PC. The port must be the same. After compilation, install it on your mobile phone. The layout file is only a textview.
Run the app, you can see "my email is ruihanL@126.com.