An Android Socket example

Source: Internet
Author: User

1. Introduction

Socket is essentially a Java encapsulation of the TCP protocol on the transport layer (Note: UDP uses the DatagramSocket class ). To implement Socket transmission, you need to build a client and a server. In addition, the transmitted data can be strings and bytes. String transmission is mainly used for simple applications. For complex applications (such as Java and C ++), you often need to build your own application layer rules (similar to the application layer protocol ), it is transmitted in bytes.

2. Socket case based on string transmission

1) server code (console-based applications, simulation)

Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. serverSocket; import java.net. socket; import java. util. arrayList; import java. util. list; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class Main {private static fi Nal int PORT = 9999; private List <Socket> mList = new ArrayList <Socket> (); private ServerSocket server = null; private ExecutorService mExecutorService = null; // thread pool public static void main (String [] args) {new Main ();} public Main () {try {server = new ServerSocket (PORT); mExecutorService = Executors. newCachedThreadPool (); // create a thread pool System. out. println ("the server has been started... "); Socket c Lient = null; while (true) {client = server. accept (); // put the client into the mList in the client collection. add (client); mExecutorService.exe cute (new Service (client); // start a new thread to handle the connection} catch (Exception e) {e. printStackTrace () ;}} class Service implements Runnable {private Socket socket; private BufferedReader in = null; private String msg = ""; public Service (Socket socket Socket) {this. socket = socke T; try {in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // the client sends the following information to the client as long as it is connected to the server. Msg = "server address:" + this. socket. getInetAddress () + "come toal:" + mList. size () + "(sent by server)"; this. sendmsg ();} catch (IOException e) {e. printStackTrace () ;}@ Override public void run () {try {while (true) {if (msg = in. readLine ())! = Null) {// when the message sent by the client is: exit, close the connection if (msg. equals ("exit") {System. out. println ("ssssssss"); mList. remove (socket); in. close (); msg = "user:" + socket. getInetAddress () + "exit total:" + mList. size (); socket. close (); this. sendmsg (); break; // receives the message msg sent from the client and sends it to the client.} Else {msg = socket. getInetAddress () + ":" + msg + "(sent by server)"; this. sendmsg () ;}}} catch (Exception e) {e. printStackTrace () ;}/ *** cyclically traverses the client set and sends information to each client. */Public void sendmsg () {System. out. println (msg); int num = mList. size (); for (int index = 0; index <num; index ++) {Socket mSocket = mList. get (index); PrintWriter pout = null; try {pout = new PrintWriter (new BufferedWriter (new OutputStreamWriter (mSocket. getOutputStream (), true); pout. println (msg);} catch (IOException e) {e. printStackTrace ();}}}}}

2) Android client code

Package com. amaker. socket; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. socket; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. OS. bundle; import android. OS. handler; import android. OS. mess Age; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. textView; public class SocketDemo extends Activity implements Runnable {private TextView TV _msg = null; private EditText ed_msg = null; private Button btn_send = null; // private Button btn_login = null; private static final String HOST = "10.0.2.2"; private static final int PORT = 9999; Private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; // the message sent by the receiving thread, use TextView to display public Handler mHandler = new Handler () {public void handleMessage (Message msg) {super. handleMessage (msg); TV _msg.setText (content) ;}}; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); TV _msg = (TextView) findViewById (R. id. textView); ed_msg = (EditText) findViewById (R. id. editText01); btn_send = (Button) findViewById (R. id. button02); try {socket = new Socket (HOST, PORT); in = new BufferedReader (new InputStreamReader (socket. getInputStream (); out = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket. getOutputStream (), true);} catch (IOException Ex) {ex. printStackTrace (); ShowDialog ("login exception" + ex. getMessage ();} btn_send.setOnClickListener (new Button. onClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub String msg = ed_msg.getText (). toString (); if (socket. isConnected () {if (! Socket. isOutputShutdown () {out. println (msg) ;}}}); // start the Thread to receive data from the server new Thread (SocketDemo. this ). start ();}/*** if an exception occurs during the connection, AlertDialog will pop up! */Public void ShowDialog (String msg) {new AlertDialog. builder (this ). setTitle ("notification "). setMessage (msg ). setPositiveButton ("OK", new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which ){}}). show ();}/*** read the information sent from the server and send it to the UI thread */public void run () {try {while (true) {if (! Socket. isClosed () {if (socket. isConnected () {if (! Socket. isInputShutdown () {if (content = in. readLine ())! = Null) {content + = "\ n"; mHandler. sendMessage (mHandler. obtainMessage ();} else {}}}} catch (Exception e) {e. printStackTrace ();}}}

Resolution: in addition to the isClose method, the Socket class also has an isConnected method to determine whether the Socket object is successfully connected. Readers may misunderstand this name. In fact, the isConnected method does not determine the current connection status of the Socket object, but whether the Socket object has been successfully connected. If the connection is successful, isConnected returns true even if isClose returns true. Therefore, to determine whether the current Socket object is connected, you must use the isClose and isConnected methods at the same time. That is, the Socket object is connected only when isClose returns false and isConnected returns true. Although you can directly use the Socket class or the close method of the input/output stream to close the network connection in most cases, sometimes we only want to disable OutputStream or InputStream, while closing the input/output stream, do not close the network connection. This requires two other methods of the Socket class: shutdownInput and shutdownOutput. These two methods only disable the corresponding input and output streams, but they do not disable the network connection function at the same time. Like the isClosed and isConnected methods, the Socket class also provides two methods to determine whether the input and output streams of the Socket object are closed. The two methods are isInputShutdown () and isOutputShutdown (). ShutdownInput and shutdownOutput do not affect the status of the Socket object.

 

2. byte-Based Transmission

When transmitting bytes, you only need to convert the corresponding string, integer, and Other types to the corresponding network bytes for transmission. For details about how to convert the data into network bytes, refer to network collection: Conversion Relationship between java integer numbers and byte [] arrays in byte order of network bytes.

 

PS: Welcome to the Android home group: 272022717. Here is a place for technical exchanges, technical support, thoughts gathering, and project exchanges.

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.