Android development-socket communication sends information to PC to obtain the IP address of the Local Machine

Source: Internet
Author: User
Tags sendmsg
The task was completed early today and we will share with you about socket programming.

Android uses the Java Socket model. If you have learned Java Network Programming, you must be familiar with it.

Today, I mainly use the TCP protocol for communication.

TIPS:The difference between the UDP protocol and the TCP protocol. UDP is to compress all data into data packets, and the data packets contain the communication address. However, after the data packets are sent, the UDP protocol cannot guarantee whether you can receive the data packets. The TCP protocol requires the receiver to send a response after receiving the data. When sending important data, you can select the TCP protocol. The amount of data sent by UDP is limited, but there is no limit on TCP. Of course, this causes UDP to be fast and TCP to be relatively slow. There are different options based on different situations.

I. Basic Structure of communication: client and server

The client side is a socket class: the client specifies to send a message to a port on a server side. For example, send a message to port 10000 of 10.10.16.162.

The server side is a servicesocket class: the server side listens on the port 10000. Once there is a message to capture it immediately, it can respond.

The client sends data to the server through outputstream, and the server obtains data through inputstream, that is, outputstream (sending) --> inputstream (receiving). The same applies if the server wants to send messages back.

Ii. Examples

 1. server side: This is a pure Java project.

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. serversocket; import java.net. socket; public class serversockettext {public static void main (string [] ARGs) {New serverthread (). start () ;}} // create a thread to listen to class serverthread extends thread {Private Static int Port = 10000; serversocket = NULL; Public void run () in the background () {try {// create a serversocket object and have it listen to serversocket = new serversocket (port); While (true) {// call the serversocket accept () method on the port, receive the request from the client Socket socket = serversocket. accept (); bufferedreader buffer = new bufferedreader (New inputstreamreader (socket. getinputstream (); // read data string MSG = buffer. readline (); system. out. println ("MSG:" + MSG) ;}} catch (ioexception e) {e. printstacktrace ();} finally {try {serversocket. close ();} catch (ioexception e) {e. printstacktrace ();}}}}

2. Client: This is an android client used to send messages.

Import Java. io. bufferedwriter; import Java. io. ioexception; import Java. io. outputstreamwriter; import Java. io. printwriter; import java.net. inetaddress; import java.net. networkinterface; import java.net. socket; import java.net. socketexception; import java.net. unknownhostexception; import Java. util. enumeration; import android. app. activity; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; public class Client extends activity {Private Static string IPaddress = "10.10.16.97"; Private Static int Port = 10000; private edittext = NULL; private button send = NULL; socket socket = NULL; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); edittext = (edittext) findviewbyid (R. id. edittext); send = (button) findviewbyid (R. id. send); send. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {sendmsg () ;}}) ;}// send message public void sendmsg () {try {// create a socket object and specify the server address and port number socket = new socket (IPaddress, Port ); // obtain the output stream printwriter out = new printwriter (New bufferedwriter (New outputstreamwriter (socket. getoutputstream (), true); // fill in information out. println (edittext. gettext (); system. out. println ("MSG =" + edittext. gettext (); // close} catch (unknownhostexception E1) {e1.printstacktrace ();} catch (ioexception E1) {e1.printstacktrace ();} finally {try {socket. close ();} catch (ioexception e) {e. printstacktrace ();}}}}

3. Notes:

Remember to add your network permissions to androidmanifest. xml.

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

The activity layout is an edittext and an existing button, so no code is pasted.

It is best to run Android on the server first, so that the client can conveniently view the message when sending it.

4. knowledge expansion: get the IP address of the Android mobile phone

As long as the IP address can be obtained, we can allow the PC and Android to implement the chat function. But here I will not demonstrate how to implement it.

 

public String getLocalIpAddress() {try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();) {NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()) {return inetAddress.getHostAddress().toString();}}}} catch (SocketException ex) {}return null;}

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.