This time in learning Android socket programming, I am not dedicated to do the app, do is bootloader, drive, HAL, the framework of this line, that is, system building and functional optimization design. In order to get through this whole line, learn a lot of things for this, today, the Android socket learning record, to prevent such a low-level error later.
I here is in the Geek Institute of the source code to do some of their own additions and modifications, the beginning of learning is not the first change, extrapolate, nature quickly learned. Because after watching the video and materials can not wait for their own ideas to do a function, but in trouble, is the implementation of the new socket (IP, port) program crashes, how to find the problem, the code can not see the problem, the head big Fast one day, the end is resolved, O (∩_∩) O. But it is also fortunate to find such a problem, will not be bothered by this problem.
The source code and related instructions are documented below.
The main use of two Java files.
Mainactivity.java:
<pre name= "code" class= "java" >package com.jikexueyuan.mysocketclient;import Android.app.activity;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.CompoundButton; Import Android.widget.edittext;import Android.widget.textview;import Android.widget.togglebutton;public class Mainactivity extends Activity {EditText IP; EditText Port; EditText EditText; TextView text; ToggleButton Connect; Button send, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main), IP = (EditText) Findviewbyid (r.id.ip);p ort = (EditText) Findviewbyid ( R.id.port); editText = (EditText) Findviewbyid (r.id.edit); text = (TextView) Findviewbyid (r.id.text); send = (Button) Findviewbyid (r.id.send); connect = (ToggleButton) Findviewbyid (r.id.connect); Connect.setoncheckedchangelistener ( New Togglebuttoncheckedchangeevent ()); Send.setonclicklistener (new Buttonclickevent ()); Connectclass.datainit (IP, port, EDittext, text, send, connect);//Pass layout data to class connectclasssend.setenabled (false);} ----------------------------------------------------Clear button, Send button class Buttonclickevent implements View.onclicklistener {public void OnClick (View v) {if (v = = send) {connectclass.send ();}}} Class togglebuttoncheckedchangeevent Implementstogglebutton.oncheckedchangelistener {@Overridepublic void OnCheckedChanged (Compoundbutton Buttonview,boolean isChecked) {if (Buttonview = connect) {if (isChecked) { Connectclass.connect (mainactivity.this);} else {connectclass.unconnect ();}}}}}
There's nothing to say about this master file, it's doing some initialization. In contrast to the geek's code, I added the ToggleButton button for connection and disconnection, plus a Port Setup window. The layout file is also posted.
Activity_main.xml:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/container "android:layout_width=" Match_parent "android:layout_height= "Match_parent" android:orientation= "vertical" > <linearlayout android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" > <edittext android: Id= "@+id/ip" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and roid:layout_weight= "1" android:hint= "Input server IP Address" android:text= "192.168.0.55" > </editte xt> <edittext android:id= "@+id/port" android:layout_width= "Wrap_content" and roid:layout_height= "Wrap_content" android:layout_weight= "0.35" android:hint= "Enter port for server" android:text= "2030" > </EDITTEXT> <togglebutton android:id= "@+id/connect" android:layout_width= "Wrap_content" Android:la yout_height= "wrap_content" android:text= "Connection" android:textoff= "@string/connect" Android:te xton= "@string/unconnect"/> </LinearLayout> <scrollview android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_weight= "0.86" > <textview android:id= " @+id/text "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "Android : text= "Ready ..."/> </ScrollView> <edittext android:id= "@+id/edit" android:layout_width= "f Ill_parent "android:layout_height=" wrap_content "android:hint=" Enter content here/> <button android:i D= "@+id/send" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "hair Send "/></lInearlayout>
The focus is Connectclass.java this type of file, the source code is as follows:
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " ></span><pre name= "code" class= "CPP" >package Com.jikexueyuan.mysocketclient;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.InputStreamReader; Import Java.io.outputstreamwriter;import Java.net.socket;import Java.net.unknownhostexception;import Android.content.context;import Android.os.asynctask;import Android.widget.button;import Android.widget.EditText; Import Android.widget.textview;import Android.widget.toast;import Android.widget.togglebutton;public class Connectclass {static Socket socket = Null;static BufferedWriter writer = null;static BufferedReader reader = null;static E Dittext ip;static EditText port;static EditText edittext;static TextView text;static Button send;static ToggleButton Conn Ect;public static void Datainit (Final EditText tIp, final EditText tport, final EditText tedittext, final TextView Ttext, Final BUtton TButton, Final ToggleButton ttogglebutton) {ip = Tip;port = Tport;edittext = Tedittext;text = Ttext;send = Tbutton;co Nnect = Ttogglebutton;} public static void Connect (final Context tactivity) {asynctask<void, String, void> read = new asynctask<void, Str ING, void> () {@Overrideprotected void Doinbackground (void ... arg0) {try {socket = new socket (Ip.gettext (). toString (), Integer.decode (Port.gettext (). toString ())), writer = new BufferedWriter (New OutputStreamWriter ( Socket.getoutputstream ()); reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));// Send.setenabled (True);p ublishprogress ("@success");} catch (Unknownhostexception E1) {Toast.maketext (tactivity, "Cannot establish link", Toast.length_short). Show ();} catch (IOException E1) {Toast.maketext (tactivity, "Cannot establish link", Toast.length_short). Show (); try {String Line;while (line = Reader.readline ())! = null) {publishprogress (line)}} catch (IOException e) {e.printstackt Race ();} return null;} @Overrideprotected void OnprogresSupdate (String ... values) {if (Values[0].equals ("@success")) {Toast.maketext (tactivity, "link succeeded!) ", Toast.length_short). Show (); send.setenabled (true);} Text.append ("Others said:" +values[0]+ "\ n"); Super.onprogressupdate (values);}; Read.execute ();} public static void Unconnect () {try {writer.close (); Reader.close (); Socket.close (); send.setenabled (false); Connect.setchecked (false);} catch (IOException e) {e.printstacktrace ();}} public static void Send () {try {text.append ("I said:" +edittext.gettext (). toString () + "\ n"); Writer.write (Edittext.gettext (). ToString () + "\ n"); Writer.flush (); Edittext.settext ("");} catch (IOException e) {e.printstacktrace ();}}}
This file class, completes the network connection, disconnects, sends the function.
This highlights the use of the new socket function, which is the cause of the crash of the title. Google found that to use the new socket this function, can not be used in the main thread UI, otherwise the error will crash, you must use a sub-thread to call the new socket function for network operation, using the Asynctask asynchronous thread, Of course, other threads are also available.
There is another cause of the crash, that is, network permissions, the configuration file must have this sentence <uses-permission android:name= "Android.permission.INTERNET"/>.
Server I use the Linux system, the source code is as follows:
/* File NAME:SERVER.C */#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno. h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define Default_port 2030 #define MAXLINE 4096 int main (int argc, char** argv) {int socket_fd, CONNECT_FD; struct sockaddr_in servaddr; Char buff[4096]; int n; Initialize socket if (SOCKET_FD = socket (af_inet, sock_stream, 0)) = =-1) {printf ("Create Socket Error:%s (errno:%d ) \ n ", Strerror (errno), errno); Exit (0); }//Initialize memset (&servaddr, 0, sizeof (SERVADDR)); servaddr.sin_family = af_inet; SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any),//IP address is set to Inaddr_any, the system automatically gets the IP address of the machine. Servaddr.sin_port = htons (default_port);//Set the port to Default_port//bind the local address to the created socket on the IF (bind (socket_fd, struct so ckaddr*) &servaddr, sizeof (servaddr)) = = 1) {printf ("Bind socket Error:%s (errno:%d) \ n",Strerror (errno), errno); Exit (0); }//Start listening for client connections if (listen (socket_fd) = =-1) {printf ("Listen socket Error:%s (errno:%d) \ n", Strerror (E Rrno), errno); Exit (0); } printf ("======waiting for client ' s request======\n"); while (1) {//block until there is a client connection, it wastes more CPU resources. if (connect_fd = Accept (socket_fd, (struct sockaddr*) null, null)) = =-1) {printf ("Accept socket Error:%s (errno: %d) ", Strerror (errno), errno); Continue }//Accept data sent by the client n = recv (connect_fd, Buff, MAXLINE, 0); Send the response data to the client if (!fork ()) {/* Forbidden City */if (send (CONNECT_FD, "Hello,you is connected!\n", 26,0) = =-1) PE Rror ("Send Error"); Close (CONNECT_FD); Exit (0); } Buff[n] = ' + '; printf ("Recv msg from client:%s\n", buff); Close (CONNECT_FD); } close (SOCKET_FD); }
The makefile file is:
Tcp_server:tcp_server.c#arm-cortex_a9-linux-gnueabi-gcc-o tcp_server tcp_server.cgcc-o tcp_server tcp_server.c
If you want to run the server on the development Board of ARM, use the commented out instructions to run it in the PC using GCC compilation.
For Linux sockets, refer to the http://blog.csdn.net/hguisu/article/details/7445768 here.
Source: http://download.csdn.net/detail/u010406724/8558445
Welcome reprint, Reprint please indicate the original address: http://blog.csdn.net/wang_shuai_ww/article/details/44835075
Android socket Learning record execution new socket (IP, port) program crashes