Android Application Software Development (15th) socket

Source: Internet
Author: User

Use a TCP-based socket
To initiate a communication, a client must first know the Host IP address of the running server. Then, the network infrastructure uses the target address to transmit the information sent by the client to the correct host. in Java, the address can be defined by a string, this string can be a numeric address (for example, 192.168.1.1) or a host name (example.com ).
In Java, the inetaddress class represents a network destination address, including host name and digital address information.

1. TCP-based socket operation API:
Serversocket: This class implements a server socket, which can be used to listen to requests from the network.

A) method for creating serversocket:
Serversocket (INT localport)
Serversocket (INT localport, int queuelimit)
Serversocket (INT localport, int queuelimit, inetaddress localaddr)
To create a serversocket, you must specify a port so that the client can send a connection request to the port. Valid port range: 0-65535

B) serversocket operations
Socket accept ()
Void close
The accept () method creates a socket instance for the next incoming connection request and returns the successfully connected socket instance to the server socket. If there is no connection request, the accept () method will block the wait;
The close method is used to close the socket.

Socket:

A) method for creating a socket:
Socket (inetaddress remoteaddress, int remoteport)

Using the socket constructor, you can create a TCP socket and connect to the specified remote address and port number first.

B) socket operation method
Inputstream getinputstream ()
Outputstream getoutputstream ()
Void close ()

Use UDP-based socket

A) create an ingress rampacket.
Datagramsocket (byte [] data, int offset, int length, inetaddress remoteaddr, int remoteport)
This constructor creates a data packet object. The data is included in the first parameter.

B) Create an initramsocket.
Datagramsocket (INT localport)
The preceding constructor creates a UDP socket;

C) sending and receiving ramsocket
Void send (datagrampacket packet)
Void receive (datagrampacket packet)
The send () method is used to send the datagrampacket instance. Once a connection is created, the datagram is sent to the connected address of the socket;
The receive () method blocks the wait, knows the received data packet, and copies the data in the packet to the specified datagrampacket instance.

Server socket: Socket. Java

Package Mars. socket; import java.net. datagrampacket; import java.net. datagramsocket; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button;/*** server socket * @ author administrator **/public class socketactivity extends activity {/** called when the activity is first created. */private button startbutton = N Ull; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); startbutton = (button) findviewbyid (R. id. startlistener); startbutton. setonclicklistener (New startsocketlistener ();} class startsocketlistener implements onclicklistener {@ overridepublic void onclick (view v) {New serverthread (). start () ;}} class serverthread extends th Read {/*** TCP-based socket * // * Public void run () {// declare a serversocket object serversocket = NULL; try {// create a serversocket object, and let the socket listen to serversocket = new serversocket (4567) on port 4567; // call the serversocket accept () method to accept the request socket = serversocket sent by the client. accept (); // obtain the inputstream object inputstream = socket from the socket. getinputstream (); byte buffer [] = new byte [1024*4]; int temp = 0; // from inputstre Am reads the data sent by the client while (temp = inputstream. Read (buffer ))! =-1) {system. out. println (new string (buffer, 0, temp) ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {try {serversocket. close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}* // *** UDP-based socket */Public void run () {try {// create a datagramsocket object, the listening port number is also specified. The value of this parameter is ramsocket socket = new datagramsocket (4567); byte data [] = new byte [1024]; // create an empty datagrampacket object named datagrampacket packet = new datagrampacket (data, data. length); // use the receive method to receive the data socket sent by the client. receive (packet); string result = new string (packet. getdata (), packet. getoffset (), packet. getlength (); system. out. println ("result --->" + result);} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();}}}}

Manifest. xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="mars.socket"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".SocketActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-sdk android:minSdkVersion="4" /><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission><uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission><uses-permission android:name="android.permission.INTERNET"></uses-permission></manifest> 

Tcpclient. Java

Package Mars; import Java. io. fileinputstream; import Java. io. inputstream; import Java. io. outputstream; import Java. io. outputstreamwriter; import Java. io. writer; import java.net. socket; public class tcpclient {public static void main (string [] ARGs) {try {// create a socket object, specify the IP address and port number of the server Socket socket = new socket ("192.168.1.104", 4567); // use inputstream to read files on the hard disk inputstream = new fileinputstream ("F: // F Ile/words.txt "); // obtain outputstreamoutputstream outputstream = socket from the socket. getoutputstream (); byte buffer [] = new byte [4*1024]; int temp = 0; // extracts data from inputstream, and write it to outputstream while (temp = inputstream. read (buffer ))! =-1) {outputstream. write (buffer, 0, temp);} outputstream. flush ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

Udpclient. Java:

Package Mars; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. inetaddress; public class udpclient {public static void main (string [] ARGs) {try {// first create a initramsocket object initramsocket socket = new initramsocket (4567 ); // create an inetaddreetaddress serveraddress = inetaddress. getbyname ("192.168.1.104"); string STR = "hello"; byte data [] = Str. getbytes (); // create a datagrampacket object and specify the address to which the packet is sent to the network and the port number datagrampacket packet = new datagrampacket (data, data. length, serveraddress, 4567); // call the send method of the socket object to send data socket. send (packet);} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

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.