Recently to do an Android project, with the socket and server interaction between the study of a small demo. The following problems have been encountered mainly:
1. The client has failed to create the socket object Networkonmainthreadexception, looked up, because after 4.0 the HTTP request in the main thread will report this error. The workaround is to put the code in a new thread, and the problem is resolved.
2. After receiving the client information, the server feeds back to the client information, which is represented in the client UI. "android.view.viewroot$calledfromwrongthreadexception:only the Original thread that created a view hierarchy can touch it views. " Abnormal. The problem is that the direct updating of the page in a thread other than the mainline thread often causes an error. The workaround is to pass the thread object through the Runonuithread method, so that the thread's contents can be executed in the main thread, but there are other ways. Refer to link http://blog.csdn.net/shenyuemei/article/details/11030679.
Here is the program code:
Layout file
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" > <EditTextAndroid:id= "@+id/content"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:hint= "@string/et_hint" /> <ButtonAndroid:id= "@+id/send"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/txt_send" /> <TextViewAndroid:id= "@+id/tv"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" /></LinearLayout>
Service-side code
PackageTestdemo;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServerImplementsRunnable { Public Static voidMain (string[] args) {Thread desktopserverthread=NewThread (NewServer ()); Desktopserverthread.start (); } @Override Public voidrun () {Try{serversocket ServerSocket=NewServerSocket (8888); while(true) { //blocked, waiting to receive customer requests. Socket client =serversocket.accept (); System.out.println ("Accepts a request to the client. "); Try{BufferedReader in=NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); //read the information sent by the client.String Read =In.readline (); System.out.println ("The client sends a message:" +read); //returning information to the clientPrintWriter out =NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Client.getoutputstream ())); if(Read! =NULL) {out.println ("The message you sent to the server is:" +read); Out.flush (); } out.close (); In.close (); } Catch(Exception e) {e.printstacktrace (); } finally{client.close (); } } } Catch(Exception e) {e.printstacktrace (); } }}
Client code
ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;Importjava.net.InetAddress;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classClientactivityextendsActivity {PrivateButton send =NULL; PrivateEditText content =NULL; PrivateTextView TV =NULL; String msg=NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.socket2); Send=(Button) Findviewbyid (r.id.send); Content=(EditText) Findviewbyid (r.id.content); TV=(TextView) Findviewbyid (r.id.tv); Send.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {settitle ("Socket"); NewThread (Thread1). Start (); } }); } /*Handler MyHandler = new Handler () {@Override public void Handlemessage (Message msg) { Myhandler.post (THREAD1); } };*/ /*** This thread is primarily sending messages and receiving messages to the server*/Runnable Thread1=NewRunnable () {@Override Public voidrun () {socket socket=NULL; Try{inetaddress serveraddr= Inetaddress.getbyname ("192.168.1.110"); Socket=NewSocket (SERVERADDR, 8888); //want the server to send messagesPrintWriter out =NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); Out.println (Content.gettext (). toString ()); Out.flush (); //read messages returned by the serverBufferedReader in =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); Msg=In.readline (); //Pass the child thread as a parameter so that the UI can be updated on the main UI threadClientactivity. This. Runonuithread (Updatethread); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } }; Runnable Updatethread=NewRunnable () {@Override Public voidrun () {if(msg! =NULL) {tv.settext (msg); } Else{Tv.settext ("Data error."); } } };}