Use socket communication

Source: Internet
Author: User

When two computer TCP/IP protocols are communicated. The socket object is usually represented on both ends of the communication interface and the network communication is made through the socket production I/O stream.

Where the ServerSocket object can receive requests from other communication entities that are connected. The purpose is to listen for the client socket connection. Assuming there is no connection, it will remain in the waiting state.

In this article, you will create a server-side socket for the ServerSocket and mobile client. Make them connect. Generates an I/O stream that displays the acquired data on the phone.

Finally get the results for example with what you see.


First build a Java project. Used to create ServerSocket. Code such as the following

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 {//Create a ServerSocket, Connection request for monitoring Clientsocket ServerSocket ss = new ServerSocket (30000); SYSTEM.OUT.PRINTLN ("Server side is ready to accept request");//Use loops to continuously receive requests from the client while (true) {//each time a Clientsocket request is received. The server side will also generate a socket object socket s = ss.accept (); OutputStream os = S.getoutputstream ();//output string. and forcibly use the UTF-8 character set for encoding Os.write ("Hello. You received a new year greeting from the server!

\ n ". GetBytes (" Utf-8 "));//close output stream, close socketos.close (); S.close ();}}}


Then build an Android project, Activity_main.xml code such as the following

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= "${packagename}.${activityclass}" >    <edittext        android:id= "@+id/show"        Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        /></relativelayout>


Mainactivity.java code such as the following

Package Com.wyb.simpleclient;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.net.socket;import Java.net.unknownhostexception;import android.app.Activity Import Android.os.bundle;import Android.widget.edittext;public class Mainactivity extends Activity {private EditText Show; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); show = (EditText) Findviewbyid (r.id.show);////Create a new thread for network operation new Thread () {@ overridepublic void Run () {try {//Establish socket socket socket connected to remote server = new Socket ("192.168.0.104", 30000);// Wraps the corresponding input stream of the socket into bufferedreaderbufferedreader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()) );//For normal I/O operation string line = Br.readline ();//The EditText control in the UI that controls the display of content Show.settext ("Data from server:" + line);//Close stream, Socketbr.close (); Socket.close ();} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}. Start ();}}

The code where 192.168.0.104 is the native IP address query native IP address can be accessed by entering CMD in the beginning of the console interface, and then enter IPconfig Press ENTER to get the relevant information.

Because network communication is used in this project. So be sure to androidmanifest.xml the access to the Internet.

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

From Android2.3 later in the version number. The Android platform does not agree to establish a network connection directly on the UI thread. Access network resources.

Therefore, it is necessary to work with the network-related operations in the new thread. Use on this project

New Thread () is going to create a fresh one. Controls the new threading UI the EditText controls what is displayed.

However, under normal circumstances. UI control on other threads is not operational. Except ProgressBar and EditText (now I know)

Use socket communication

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.