Android development _ socket (2)

Source: Internet
Author: User
Socket programming 1. Basic Introduction

Socket"

Socket is also known as "socket". It is used to describe IP addresses and ports and is a communication chain handle.

Applications usually send requests to or respond to network requirements through "Sockets ".

 

 

 

2. scoket basic communication model

 

Serversocket ______________________________________________ server end including TCP and UDP
Package COM. example. socket_server; import Java. io. inputstream; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. serversocket; import java.net. socket; import android. app. activity; import android. database. mergecursor; import android. OS. bundle; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onclicklistener; import android. widget. Button; public class socketserveractivity extends activity {private button start_socket; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_socket_server); // start uistart_socket = (button) findviewbyid (R. id. socketserver); start_socket.setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view arg0) {// todo Auto-generated method stubnew serverthread (). start () ;}}) ;}// TCP/* class serverthread extends thread {@ overridepublic void run () {// todo auto-generated method stubsuper. run (); serversocket mserversocket = NULL; try {// create a serversocket and let the socket listen to mserversocket = new serversocket (1234) on port 1234; log. D ("mydebug", "now waiting serverscoket. accept ()! "); Socket msocket = mserversocket. accept (); inputstream minputstream = msocket. getinputstream (); byte buffer [] = new byte [1024*4]; int temp = 0; while (temp = minputstream. read (buffer ))! =-1) {log. D ("mydebug", "Now is printing the string! "); System. out. println (new string (buffer, 0, temp) ;}} catch (exception e) {e. printstacktrace ();} finally {try {mserversocket. close ();} catch (exception e) {e. printstacktrace () ;}}} * // udpclass serverthread extends thread {@ overridepublic void run () {// todo auto-generated method stubsuper. run (); try {datagramsocket Socket socket = new datagramsocket (1234); byte data [] = new byte [1024*4]; datagrampacket packet = new datagrampacket (data, data. length); socket. receive (packet); string result = new string (packet. getdata (), packet. getoffset (), packet. getlength (); system. out. println ("result ------------>" + result);} catch (exception e) {e. printstacktrace () ;}}@ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). inflate (R. menu. activity_socket_server, menu); Return true ;}}
3. TCP-based scoket
package client;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;public class Client_TCP {private String str = "abcdefghijklnopqrstuvwxyz!";public static void main(String[] args) {try{Socket mSocket = new Socket("192.169.0.1", 1234);InputStream mInputStream = new FileInputStream("I:\\1.txt");OutputStream mOutputStream = mSocket.getOutputStream();byte buffer[] = new byte[1024*4];int temp = 0 ;while((temp = mInputStream.read(buffer)) != -1){mOutputStream.write(buffer, 0, temp);}mOutputStream.flush();}catch(Exception e){e.printStackTrace();}}}
4. UDP-based scoket
package client;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class Client_UDP {public static void main(String[] args) {try {DatagramSocket socket = new DatagramSocket(1234);InetAddress serverAddress = InetAddress.getByName("192.168.0.1");String str = "abcdefghijkmnopqstuvwyz";byte data[] = new byte[1024 * 4];data = str.getBytes();DatagramPacket packet = new DatagramPacket(data, data.length, 1234);socket.send(packet);} catch (Exception e) {e.printStackTrace();}}}
 
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.