Android --- 51 --- added multi-thread Socket communication and androidsocket Multithreading

Source: Internet
Author: User

Android --- 51 --- added multi-thread Socket communication and androidsocket Multithreading

The front server and client only perform simple communication operations: After the server receives the Client Connection
The server outputs a string to the client, and the client exits after reading the Server String.

In actual applications, the client may need to maintain long-time communication with the server, that is, the server
The client needs to constantly read client data and write data to the client.
Read the server and write data to the database.


When the traditional BufferedReader readLine method is used to read data, the thread
Is blocked, and the program cannot continue. Therefore, the server should enable one thread for each Socket, and each thread
Communicates with a client.


Server:

 

class ServerThread implements Runnable {Socket s;BufferedReader br;public ServerThread(Socket s) throws IOException {super();this.s = s;br = new BufferedReader(new InputStreamReader(s.getInputStream()));}@Overridepublic void run() {String content = null;try {while ((content = readFromClient()) != null) {for (Socket s : MultiThreadServer.sockets) {OutputStream os;os = s.getOutputStream();os.write((content + "\n").getBytes("utf-8"));}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private String readFromClient() {try {return br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}public class MultiThreadServer {public static ArrayList<Socket> sockets = new ArrayList<Socket>();public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(45623);while (true) {Socket s = ss.accept();sockets.add(s);new Thread(new ServerThread(s)).start();}}}


 

After the client Socket is connected to the ServerSocket,
The program adds the corresponding Socket to the set for saving, and opens a thread for the Socket, responsible for processing the Socket
All communication transactions.


Client:

 

MultiClient:

 

 

Public class MultiThreadClient extends Activity {EditText input; TextView show; Button send; Handler handler; ClientThread clientThread; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_client_thread); input = (EditText) findViewById (R. id. input); show = (TextView) findViewById (R. id. show); send = (Button) findViewById (R. id. send); handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// if the Message comes from the subthread if (msg. what = 0x123) {// append the read content to show in the text. append ("\ n" + msg. obj. toString () ;}}; clientThread = new ClientThread (handler); // The client starts the ClientThread Thread to create a network connection and read data from the server new Thread (clientThread ). start (); send. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// when the user presses the send button, the data entered by the user is encapsulated into a Message, then the handlerMessage msg = new Message (); msg sent to the subthread. what = 0x345; msg. obj = input. getText (). toString (); clientThread. revHandler. sendMessage (msg); input. setText ("");}});}}


 

ClientThread:

 

Public class ClientThread implements Runnable {private Socket s; // defines the Handler object that sends messages to the UI thread. Private Handler handler; // defines the Handler object that receives messages from the UI thread. public Handler revHandler; // The Stream object BufferedReader br used by the Socket processed by this thread; OutputStream OS; public ClientThread (Handler handler) {super (); this. handler = handler;} @ Overridepublic void run () {try {s = new Socket ("192.168.3.12", 45623); br = new BufferedReader (new InputStreamReader (s. getInputStream (); OS = s. getOutputStream (); // start a sub-Thread new Thread () {public void Run () {String content = null; // continuously read the content in the Socket input stream try {while (content = br. readLine ())! = Null) {// after reading data from the server, the Message notification program interface displays the data Message msg = new Message (); msg. what = 0x123; msg. obj = content; handler. sendMessage (msg) ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}};}. start (); // initialize LooperLooper for the current thread. prepare (); // create the revhandler object revHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// receives user input data in the UI thread if (msg. what = 0x345) {// write the content entered by the user in the text box to the network try {OS. write (msg. obj. toString () + "\ r \ n "). getBytes ("UTF-8");} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}}; logoff. loop ();} catch (IOException 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.