Android self-study course-simple use of Socket, android course socket

Source: Internet
Author: User

Android self-study course-simple use of Socket, android course socket

I haven't updated my blog for several days. I thought it was easy to attend too many school classes .. Second, I encountered a lot of problems in the instance operation process, but it was okay to solve them... Again, it's not long before the second-level C language examination, and there are still 20 days to estimate. You haven't come and read it !!!! Time management is lacking ~~ So much nonsense. Let's start our instance drills. I also hope you can give me some advice and learn from new users.

 

This knowledge is not isolated, including Socket programming, multi-threaded operations, and I/O Stream operations. Of course, there are more than one implementation method, which is just one of them. It gives a new beginner a little idea. If you have any suggestions, please kindly advise!

 

Let's take a look at the application interface to get a general idea of its functions.

The pictures are big enough to look good.

 

Activity_main.java

1 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 2 xmlns: tools = "http://schemas.android.com/tools" 3 android: layout_width = "match_parent" 4 android: layout_height = "match_parent" 5 android: orientation = "vertical" 6 tools: context = ". mainActivity "> 7 8 <EditText 9 android: id =" @ + id/editText "10 android: layout_width =" match_parent "11 android: layout_height =" wrap_content "12 android: hint = "Enter the content to be sent"/> 13 14 <Button15 android: id = "@ + id/button01" 16 android: layout_width = "match_parent" 17 android: layout_height = "wrap_content" 18 android: text = ""/> 19 20 <Button21 android: id = "@ + id/button02" 22 android: layout_width = "match_parent" 23 android: layout_height = "wrap_content" 24 android: text = "send"/> 25 26 <ScrollView27 android: layout_width = "match_parent" 28 android: layout_height = "wrap_content" 29 android: scrollbars = "vertical" 30 android: fadingEdge = "vertical"> 31 <TextView32 android: id = "@ + id/textView" 33 android: layout_width = "match_parent" 34 android: layout_height = "wrap_content" 35 android: text = "output:"/> 36 </ScrollView> 37 38 </LinearLayout>

 

The interface is very simple.

 

Next we need a server and a client. Server, I use the Java Server written by Eclipse; client, I use Android Studio.

Package com. ryan. socketdemo01; import android. OS. handler; import android. OS. message; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; import java. io. IOExcepti On; import java. io. outputStream; import java. io. unsupportedEncodingException; import java.net. socket;/*** function of this instance: the client sends data to the client (Dynamic Output Data) **/public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button button01 = null; private Button button02 = null; private EditText editText = null; private TextView textView = null; private static Socket ClientSocket = null; priva Te byte [] msgBuffer = null; Handler handler = new Handler (); private void initView () {button01 = (Button) findViewById (R. id. button01); button02 = (Button) findViewById (R. id. button02); editText = (EditText) findViewById (R. id. editText); textView = (TextView) findViewById (R. id. textView); button01.setOnClickListener (this); button02.setOnClickListener (this); button01.setEnabled (true); button02.setEnab Led (false) ;}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView () ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. button01: // TODO: 15-9-4 socket connection thread connectThread (); break; case R. id. button02: // TODO: 15-9-4 data sending thread sendMsgThread (); break;} private void sendMsgThread (){ Final String text = editText. getText (). toString (); try {msgBuffer = text. getBytes ("UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} new Thread (new Runnable () {@ Override public void run () {try {OutputStream outputStream; // Socket output stream outputStream = ClientSocket. getOutputStream (); outputStream. write (msgBuffer); outputStream. flush (); outputStream. close ();} catch (IOExcep Tion e) {e. printStackTrace ();} handler. post (new Runnable () {@ Override public void run () {textView. append ("sent successfully:" + text + "\ n ");}});}}). start ();} private void connectThread () {new Thread (new Runnable () {@ Override public void run () {try {ClientSocket = new Socket ("10.0.2.2 ", 9001); if (ClientSocket. isConnected () {handler. post (new Runnable () {@ Override public void run () {textView. append (" Connection successful! "+" \ N "); button01.setEnabled (false); button02.setEnabled (true) ;});} else {handler. post (new Runnable () {@ Override public void run () {textView. append ("connection failed! "+" \ N ") ;}} 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. 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 (); // noinspection SimplifiableIfStatement if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item );}}

 

Here, my thread usage is:

new Thread (new Runnable) {      @Override      public void run() {      }  }    

 

Some people on the Internet say this method is very LOW and not good, but now I only know this, and even asynctask is still learning.

 

 

Also, the sub-thread method for updating the main UI is as follows:

I am using Handler. post (); it is also very simple to use.

Handler handler = new Handler (); handler. post (new Runnable () {@ Override public void run () {textView. append ("sent successfully:" + text + "\ n ");}});

 

I will write another blog about how several sub-threads update the main UI. I already know no more than 4 methods, but I have not done it on the fly yet.

 

The method for I/O Stream operations is as follows:

I will not introduce it in detail here. You can Google it on your own! What, you don't know about Google? Find the FQ tool ~~

Here I will talk about my simple use of I/O.

Everything started from the beginning. InputStream and OutputStream have only reader () and write () methods (). In addition, for example, the most frequently used BufferedReader objects are all upgraded packages on top of them. wearing a dress makes them more gorgeous. His professional term is the decorator model. If you are interested, you can flip through the materials.

The image pixels are good, right...

At first, I was not very clear about the InputStream and OutputStream methods. I often mistakenly used the write () method for InputStream. I do not know where to see such a passage. The operation of the I/O Stream is actually relative to the Socket, the Data Stream pipeline generated after the ServerSocket connection, reader and write are the meaning of reading and writing, operations are performed relative to the Data Stream pipeline. Read the information in the MPs queue and write the information to the MPs queue. I don't know.

 

The last step is the Socket we want to learn.

Its usage is also very simple. It creates a Socket object, sets the IP address and port, and obtains its I/O Stream.

ClientSocket = new Socket("10.0.2.2",9001);outputStream = ClientSocket.getOutputStream();

 

 

There are so many basic usage methods here.

Let's talk about the problems I encountered here:

1. The simulator cannot connect to the Java Server. The Ip address is set incorrectly. The Ip address I first set is 127.0.0.1. Resolved connections:

Http://stackoverflow.com/questions/8191192/reaching-a-network-device-by-ip-and-port-using-the-android-emulator/8191487#8191487

Http://stackoverflow.com/questions/10336637/how-do-i-socket-an-android-program-to-a-localhost-server

 

2. You forgot to set manifest, or the android. permission. INTERNET provided by the system is in uppercase !! It's funny, but I encountered such a problem. The Code prompts automatically completed by the system are all in uppercase. I thought that was the case and the results should be in lower case.

<uses-permission android:name="android.permission.INTERNET" />

 

 

I forgot to paste the code of the java Server.

/*** Function of this instance: Accept data sent from the server */public class Main {public static void main (String [] args) {// TODO Auto-generated method stub new SerVerListener (). start ();}}

 

Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. unsupportedEncodingException; import java.net. serverSocket; import java.net. socket; import javax. swing. JOptionPane; public class SerVerListener extends Thread {private Socket clientSocket = null; private ServerSocket serverSocket = null; private InputStream inputStream = n Ull; private byte [] buffer = null; @ Override public void run () {// TODO Auto-generated method stub try {serverSocket = new ServerSocket (9001); System. out. println ("port enabled, waiting for connection ~ ~"); // block clientSocket = serverSocket. accept (); System. out. println ("existing user connection"); inputStream = clientSocket. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (inputStream); String str; while (st R = br. readLine ())! = Null) {System. out. println (str) ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {try {inputStream. close (); serverSocket. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}

 

This is the data received by the server:

 

 

OK, basically. After learning, I will share it with you again, Tom ....

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.