Android and PC side via WiFi communication

Source: Internet
Author: User
Tags linux mint

Pre-preparation: My Linux Mint operating system (in short toss the process of suspected is not a system problem), the first is to create a WiFi hotspot for Android phone use, this time notebook as a communication server side, Android phone as a client, communicates through the socket.

1. Write the server-side code under Eclipse, including listening port good, client IP address acquisition, sending data processing, etc., here involves the environment configuration of the Java EE, there is time I write, this code is direct Baidu to, can use:

ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTest {PrivateServerSocket server; PrivateSocket Client; PrivateBufferedReader in; PrivatePrintWriter out;  PublicTest () {Try{Server=NewServerSocket (9400);  while(true) {System.out.println ("Start! "); //Get client ConnectionsClient =server.accept (); //get the IP and port of the clientString Remoteip =client.getinetaddress (). gethostaddress (); intRemotePort =Client.getlocalport (); System.out.println ("A client connected." IP: "+Remoteip+ ", Port:" +remoteport);                System.out.println (); //gain client-side input and output streams to prepare for interactionin =NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); out=NewPrintWriter (Client.getoutputstream (),false); //get data sent from client sideString tmp =In.readline (); //String content = new String (Tmp.getbytes ("Utf-8"));SYSTEM.OUT.PRINTLN ("Client message is:" +tmp); //send response data to client sideOUT.PRINTLN ("Your message has been received successfully!."); //Close individual streamsOut.close ();                In.close (); //server.close ();            }        } Catch(Exception e) {//send response, receive failedSystem.out.println (e.tostring ()); Out.println ("Receive error!"); }    }     Public Static voidMain (string[] args) {NewTest (); }}

The code does not look too difficult, the key is the use of Java EE, especially the configuration of the server (configuration tutorial involves the configuration of Tomcat, and the establishment of the server).

Project name is ready to be written, then next---->next, generate Web. XML deployment descriptor should be selected. Attention:

Java Resources under the SRC folder is the relevant class, after the class is written in the WebContent folder--->web-inf folder under the Web. XML inside the configuration:

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"ID= "webapp_id"version= "3.0">    <Display-name>Tomcattest</Display-name>    <welcome-file-list>        <Welcome-file>Index.html</Welcome-file>        <Welcome-file>Index.htm</Welcome-file>        <Welcome-file>index.jsp</Welcome-file>        <Welcome-file>Default.html</Welcome-file>        <Welcome-file>Default.htm</Welcome-file>        <Welcome-file>default.jsp</Welcome-file>    </welcome-file-list>    <servlet>        <Servlet-name>Test</Servlet-name>        <Servlet-class>Test</Servlet-class>    </servlet>    <servlet-mapping>        <Servlet-name>Test</Servlet-name>        <Url-pattern></Url-pattern>    </servlet-mapping></Web-app>
View Code

Here you can run your server, check the project, right click on the run as--->run on server, to this your site basically published successfully, in your phone's browser to enter your PC IP address, note that the port number is 9400, For example, I used to test the 10.3.19.26:9400, you can see the information returned by the server.

2.android end of the program is relatively simple, but in the beginning, how can not run successfully, the last two problems found in a. Permissions are not added, B. Since android3.0, the operating mechanism of Android does not allow the use of network-related operations in the main thread

My value added these permissions, seemingly can also run up, hehe:

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

The second question, some of the online code is too pit, obviously have problems, do not know the changes, the following is very simple to write, no graphical interface,

 Packagecom.example.client;Importjava.io.IOException;ImportJava.io.PrintStream;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateButton Btnconnect, btnsend; Privatesocket socket; PrivatePrintStream output; PrivateEditText Editsend; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Btnconnect=(Button) Findviewbyid (R.id.button1); Btnsend=(Button) Findviewbyid (R.id.button2); Editsend=(EditText) Findviewbyid (R.ID.EDITTEXT1); Btnconnect.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub                NewThread (runnable). Start ();//Open Thread}}); Btnsend.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubSendMessage (Editsend.gettext (). toString ());    }        }); } Runnable Runnable=NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubInitclientsocket ();    }    };  Public voidInitclientsocket () {Try{EditText edit_ip= (EditText) mainactivity. This. Findviewbyid (R.ID.EDITTEXT2); String IP=Edit_ip.gettext (). toString (). Trim (); Socket=NewSocket ("10.3.19.26", 9400); Output=NewPrintStream (Socket.getoutputstream (),true, "GBK"); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockToast.maketext (mainactivity. This, "Please check if the port number is a server IP", Toast.length_long). Show ();        E.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockToast.maketext (mainactivity. This, "The server is not turned on", Toast.length_long). Show ();        E.printstacktrace (); } output.println ("The Message from client"); }    Private voidsendMessage (String str) {output.println (str); }     Public voidclosesocket () {Try{output.close ();        Socket.close (); } Catch(IOException e) {System.out.println ("Error" +e); }    }}

Basically the control has only one button, the other is useless, in the button listener is written in the method, is to use runable to open a thread, in the Runable method call Initclientsocket () method, you will find that the connection code is very simple, I use it when I connect successfully

Output.println ("This was the message from client");

This is the information returned to the server, the first place in the other button, but in view of the above problem, or directly in the thread (I have tested, in the UI threads can not use this method, sent out and no response) the final server-side accepted data is as follows:

From afternoon to night. 2015-05-18 22:11:21, there is time to get the relevant configuration down.

Android and PC side via WiFi communication

Related Article

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.