PC do the server, Android do the client.
Android Gets the contents of the input box and sends it, and then waits for the message to receive the server
The server first opens, receives the client's data, and then replies to the message.
Implements encapsulation of thread classes, sends and receives by button initiation thread
Server Code (Java Edition):
ImportJava.io.*;Importjava.net.*;/*requirements: Define the endpoint to receive the data and print it on the console server: 1. Create a server-side ServerSocket object and specify the port when not specified, use the Connect method to specify 2. Gets the client object that is connected to wait through ServerSocket's Accept method , blocking, no connection Waits 3. If the client sends over the data, the server uses the corresponding connection to read the stream to get the data printed at the service desk 4, close the server side (optional)*/ classtcpserver{ Public Static voidMain (string[] args)throwsioexception{//set up a service-side socket service and listen for portsServerSocket SS =NewServerSocket (30000);//using loops to continuously accept requests from clients while(true) { //Get the Client object (content, port, IP attribute) from the link through the Accept methodSocket s =ss.accept (); /*Receive phone data*/ //IP:String IP =s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+"... Connection Successful " ); //content: Gets the data sent by the client, then uses the client object sInputStream in =S.getinputstream (); byte[] buf =New byte[1024]; intlen=In.read (BUF); String content=NewString (buf,0, Len); System.out.println ("Content:" +content); /*send back phone data*/outputstream OS=S.getoutputstream (); Os.write ("Welcome back to learn Android, you have received the blessing of bubbles!" \ n ". GetBytes ("Utf-8")); //s.close ();//shut down the client, the server can control the customer//ss.close ();//close the server, optional operation}}}Tcpserver.java
Android Code (Android version):
Background code:
Packagecom.simpleclient;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateEditText Medittext =NULL; PrivateTextView Mtextview =NULL; PrivateButton Mbutton =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mbutton=(Button) Findviewbyid (R.id.mbutton); Medittext=(EditText) Findviewbyid (R.id.medittext); Mtextview=(TextView) Findviewbyid (R.id.mtextview); Mbutton.setonclicklistener (NewStartsocketlistener ()); } //Start button Monitoring classStartsocketlistenerImplementsonclicklistener{@Override Public voidOnClick (View v) {NewServerthread (). Start (); } } classServerthreadextendsthread{//TCP Protocol@Override Public voidrun () {socket socket=NULL; Try { /*Specify the IP address of the server, this address is the LAN address, if you are using WiFi internet access, the WiFi IP address of the PC * The IP address seen in Ipconfig is as follows: * Ethern ET adapter Wireless network connection: * connection-specific DNS Suffix. : IP address ... ...: 192.168.1.100*/ //1 Setting up a socket connected to a remote serverSocket =NewSocket ("192.168.1.108", 30000);//①LOG.D ("TCP", "c:connecting ..."); //2 sending data to the serverBufferedWriter Bufwriter =NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); //Send user-entered content to the serverString Linewrite =Medittext.gettext (). toString (); LOG.D ("TCP", "c:sending: '" + linewrite + "'"); Bufwriter.write (linewrite);//sending data to the serverBufwriter.newline (); Bufwriter.flush (); //3 Receiving server information//wraps the input stream corresponding to the socket into a bufferedreaderBufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //perform normal IO operations to get server informationString line =Br.readline (); Mtextview.settext ("Read data from the server:" +Line ); //close the input stream, socketBr.close (); //socket.close (); } Catch(unknownhostexception e) {LOG.E ("TCP errror", "192.168.1.108 is Unkown server!"); } Catch(Exception e) {e.printstacktrace (); } finally { Try{socket.close (); } Catch(Exception e) {e.printstacktrace (); } } } }}Mainactivity.java
Front Code:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "Vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent" ><!--get input box information and send it out--<EditText Android:id= "@+id/medittext"Android:layout_width= "Fill_parent"Android:layout_height= "40DP"android:cursorvisible= "false"android:editable= "true"Android:ems= "Ten" > </EditText> <TextView Android:id= "@+id/mtextview"Android:layout_width= "Fill_parent"Android:layout_height= "50DP"Android:ems= "Ten" > </TextView> <Button Android:id= "@+id/mbutton"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "TCP Client---send"/></linearlayout>
Activity_main.xml
Permission code:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.simpleclient"Android:versioncode= "1"Android:versionname= "1.0" > <uses-SDK Android:minsdkversion= "14"android:targetsdkversion= "/>" <uses-permission android:name= "Android.permission.INTERNET"/> <Application Android:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <Activity Android:name=". Mainactivity "Android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MA In "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter& Gt </activity> </application></manifest>
Use_permisson
Effect:
Problem: Garbled problem has not been solved ~
Android TCP Communication version 2