Andriod socket programming

Source: Internet
Author: User
Tags ftp protocol
Why socket? Because I have read my Bluetooth protocol (1) and Bluetooth protocol (2) Article People know that the application I want to do is to read the data in the Bluetooth pen into the mobile phone, and the socket based on the Bluetooth protocol will be used, that's why I want to talk about socket programming here. I. What is socket? It is actually an interface for network communication. Based on different protocols, there are various sockets, for example, a socket based on the TCP protocol, a socket based on the UDP protocol, and a socket based on the Bluetooth protocol, Android uses the Java Socket model. In the computer industry, socket is often called "socket". It is used to describe IP addresses and ports and is a communication chain handle. This is a relatively abstract concept. A computer has a port. Each port can have an application. Program For example, port 80 is the port used by the HTTP protocol, port 21 is the port used by the FTP protocol, and port is the interface for communication between the computer and the outside world, these interfaces are all logical interfaces. The port number ranges from 0 to 256 multiplied by 256 minus and below are reserved ports used by the operating system. We can use the above ports freely, do not conflict with the ports of other applications. An application can send a request to or respond to a network request through a "socket". At this time, the socket is divided into two parts, one of which is the socket at the server end, this socket is mainly used to receive requests from the network. It has been listening to a port. One part is the socket of the client, which is mainly used to send data to the network. Ii. Socket Communication Model

-Udp, TCP, and TCP are the two most widely used protocols on the Internet, both of which are IP-based. The first difference is that the UDP protocol is not very reliable. The UDP Protocol divides all data into data packets, and the packet comes with the communication address, that is to say, which address I want to send this packet to on the network and send it out through the network. Whether the packet is sent to the destination or whether the server receives the packet, this agreement is not guaranteed. Just like China Post, you sent the mail, but the postal system does not guarantee that the recipient can receive the mail you sent. When sending data over TCP, the receiver is required to send a response after receiving the data, that is, whether or not you have received the data. TCP is more reliable, TCP is generally used when we send important data. Another difference is that the capacity of a packet sent by the UDP protocol is limited, while the TCP protocol does not. It does not mean that the UDP protocol must be inferior to the TCP protocol. It is used in different fields. The advantage of the UDP protocol is that the speed is relatively faster. TCP is relatively slow. -The socket communication process application can select one of the two Protocols through "socket", that is, the SOCKET protocol. You can use UDP to send data or TCP to send data, data is sent to the server (receiving end) through the "communication channel", that is, the basic network of the IP address. The UDP protocol is used for sending data, and UDP protocol is used for receiving data. TCP protocol is used for sending data, and TCP protocol is used for receiving data, you can specify the IP address and port number of the receiver when sending data packets or data. The framework has helped us encapsulate the data packets or data. I. TCP Communication Model 1: Workflow

First, there are two parts of the client and the server, the client needs the socket class object, and the server needs the serversocket class object, the client socket sends a request, the serversocket on the server listens to a port number on the computer. After listening to the requests sent by the client, a communication channel between the client and the server is established, at this time, you can send data from the client to the server, and the server can also send the corresponding response to the client. When sending data from the client, we need to use outputstream In the IO stream to send the data to the server through this outputstream. The server uses inputstream to read the data written by the client using outputstream. Example of life: Just like a friend or a man who calls a phone, a boy (client) speaks (data) and sends it to the telephone network through a receiver, when a boy speaks, it is equivalent to writing data to the Internet through outputstream. As the girl who answers the question (server side), the boy (client side) the content is what girls (servers) Hear. That is to say, the server can use inputstream to read the data written in the client through outputstream, and vice versa, if the server wants to send data to the client, it uses outputstream to write data, and the client reads the data written by outputstream on the server through inputstream. Just like making a phone call, what you say is what I listen to, and what you listen to is what I say. Ii. Send and read data through the TCP protocol 1: Layout file main. xml
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <button Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Start listening thread" Android: Id = "@ + ID/btn1"/> </linearlayout>

2.1: server socketCodeFile mainactivity. Java
Package COM. szy. socket; 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 Java. io. ioexception; import Java. io. inputstream; import java.net. serversocket; import java.net. socket; public class mainactivity extends activity {private button btn1 = NULL; @ override public Void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); btn1 = (button) findviewbyid (R. id. btn1); // bind the listener btn1.setonclicklistener (New btn1listener ();} // The private class btn1listener of the button listener implements onclicklistener {@ override public void onclick (view V) {// start a thread new serverthread (). start () ;}// Thread class private class serverthread extends thre Ad {public void run () {// declare a serversocket object serversocket = NULL; try {// create a serversocket object, and let serversocket listen to serversocket = new serversocket (4567) on port 4567; // call the accept () method of the serversocket object to receive the request sent by the client // accept () this method is a blocking method. If the client does not send a request, the code runs here and is blocked. It stops running here and waits until the accept () function returns, at this time, the client suddenly sends a request, and this method will return the socket object, // The socket object represents a connection between the server and the client socket = serversocket. accept (); // from sock Get the inputstream object in the et object // once the communication pipeline is established, there is a socket on the server side, and the client also has a socket, we can use the inputstream in the socket on the server side to read the data inputstream = socket sent by the client. getinputstream (); byte data [] = new byte [1024*4]; int I = 0; // read the data sent by the client from the inputstream object while (I = inputstream. read (data ))! = 1) log. D ("mytag", new string (data, 0, I);} catch (ioexception e) {e. printstacktrace ();} finally {try {serversocket. close ();} catch (ioexception e) {e. printstacktrace ();}}}}}

2.2: client socket code file tcpsocketclient. Java

Package COM. szy. socketclient; import android. app. activity; import java.net. socket; import Java. io. fileinputstream; import Java. io. inputstream; import Java. io. outputstream; public class tcpsocketclient extends activity {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.105", 4567); // use the inputstream object to read files on the hard disk inputstream = N EW fileinputstream ("C: // www.txt"); // obtain the outputstream object from the socket object and prepare to write data to the outputstream object outputstream = socket. getoutputstream (); byte data [] = new byte [1024*4]; int I = 0; while (I = inputstream. read (data ))! = 1) // read data from the inputstream object and write it to the outputstream object. write (data, 0, I); outputstream. flush ();} catch (exception e) {e. printstacktrace ();}}}

(Android bus exit)

welcome to join the group to learn and make progress together! Shenzhen group 260134856 : Chengdu group 252743807 , beijing group 111059554 , Xi'an group 252746034 , Wuhan group 121592153 , hangzhou group 253603803

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.