Android implements Instant Messaging Based on TCP and UDP protocols, including android and Server
I have learned how to implement instant messaging in android over the past few days. At the beginning, I naturally tried it from the basic network protocols, so that I can customize my own applications to the maximum extent, you can also learn more about the two Protocols and enjoy more benefits. Next, let's briefly introduce the differences between the two Protocols.
TCP: provides reliable data transmission in an IP environment. It provides services including data stream transmission, reliability, effective traffic control, full-duplex operations, and multiplexing. Send data packets through connection-oriented, end-to-end, and reliable data packets. For example, when talking to the two people on the cliff, he must first build the bridge and confirm that the bridge is OK before handing over the letter, confirm that there is no problem with the bridge, and then communicate back and forth through the bridge.
UDP protocol: it does not provide reliability, traffic control, or error recovery functions for IP addresses. before formal communication, you do not need to establish a connection with the other party, and send the connection directly regardless of the other Party's status. This is the Flying Pigeon book ~
Although UDP is less reliable than TCP, the communication efficiency is higher than TCP. UDP protocol is preferred when the network speed is very poor. If the network speed is good, TCP is very convenient to use.
Using TCP in Java, you can use java.net. Socket; this class
Establish a connection
// Instantiate a Socket object socket = new Socket (); // connect to the corresponding ip address and port, and build the socket first. connect (new InetSocketAddress (ip, port), 3000 );
Send information
InputStream ois = socket. getInputStream (); DataInputStream dis = new DataInputStream (new BufferedInputStream (ois); // read the information sent from the server. If no information is available, the thread msg = dis will be blocked. readUTF ();
Send information
// Obtain the output stream DataOutputStream dos = new DataOutputStream (new BufferedOutputStream (socket. getOutputStream (); // send data dos. writeUTF (msg );
Next, the source code is the sub-classes of the three threads, which correspond to the above three
Public class SocketThread extends Thread {private Socket socket; private Client client; private String ip; private int port; private boolean isStart = false; private MessageListener mMessageListener; /***** use the TCP protocol, connect to the * @ param ip address IP address of the target machine * @ param port * @ param mMessageListener. When receiving server data, the * public void Message (String msg) in this interface will be called back) method */public SocketThread (String ip, int port, MessageListener mMessageListener) {this. ip = ip; this. port = port; this. mMessageListener = mMessageListener;} public void run () {try {// instantiate a Socket object socket = new Socket (); // connect to the corresponding ip address and port, first, build the socket for the bridge. connect (new InetSocketAddress (ip, port), 3000); if (socket. isConnected () {System. out. println ("Connected .. "); client = new Client (socket, mMessageListener); // open the corresponding input/output stream listener client. start (); isStart = true ;}} catch (IOException e) {e. printStackTrace (); isStart = false ;}// directly obtain the read thread public ClientInputThread getClientInputThread () {return client through the client. getIn () ;}// get the write thread public ClientOutputThread getClientOutputThread () {return client directly through the client. getOut () ;}// return the Socket state public boolean isStart () {return isStart ;}// stop the public void setIsStart (boolean isStart) {this. isStart = isStart; client. getIn (). setStart (isStart); client. getOut (). setStart (isStart);} // send the message public void sendMsg (String msg) {client. getOut (). sendMsg (msg);} public class Client {private ClientInputThread in; private ClientOutputThread out; public Client (Socket socket, MessageListener mMessageListener) {// use this listening input stream thread to receive information in = new ClientInputThread (socket); in. setMessageListener (mMessageListener); // later, the thread that listens to the output stream will be used to send information out = new ClientOutputThread (socket);} public void start () {in. setStart (true); out. setStart (true); in. start (); out. start () ;}// get the read message thread public ClientInputThread getIn () {return in ;}// get the write message thread public ClientOutputThread getOut () {return out ;}}}
Public class ClientInputThread extends Thread {private Socket socket; private String msg; private boolean isStart = true; private InputStream ois; private DataInputStream dis; private MessageListener messageListener; // message listening interface object public ClientInputThread (Socket socket) {this. socket = socket; try {ois = socket. getInputStream (); dis = new DataInputStream (new BufferedInputStream (ois);} catch (IOException e) {e. PrintStackTrace () ;}}/*** message listening method provided to external users ** @ param messageListener * message listening interface object */public void setMessageListener (MessageListener messageListener) {this. messageListener = messageListener;} public void setStart (boolean isStart) {this. isStart = isStart;} @ Overridepublic void run () {try {while (isStart) {// read information. If no information is available, the thread msg = dis will be blocked. readUTF (); // call the interface method Message (String msg) Log every time a Message is received. v ("Receive message", msg); message Listener. Message (msg);} ois. close (); if (socket! = Null) socket. close ();} catch (IOException e) {e. printStackTrace () ;}} BufferedReader reader = null; public String getInputStreamString () {/** To convert the InputStream to String we use the * BufferedReader. readLine () method. we iterate until the BufferedReader * return null which means there's no more data to read. each line will * appended to a StringBuilder and returned as String. */if (ois! = Null) {reader = new BufferedReader (new InputStreamReader (ois);} StringBuilder sb = new StringBuilder (); String line = null; try {while (line = reader. readLine ())! = Null) {sb. append (line + "\ n") ;}} catch (IOException e) {e. printStackTrace () ;}return sb. toString ();}}
Public class ClientOutputThread extends Thread {private Socket socket; private DataOutputStream dos; private boolean isStart = true; private String msg; public ClientOutputThread (Socket socket) {this. socket = socket; try {dos = new DataOutputStream (new BufferedOutputStream (socket. getOutputStream ();} catch (IOException e) {e. printStackTrace () ;}} public void setStart (boolean isStart) {this. isStart = isSt Art;} // The public void sendMsg (String msg) {this. msg = msg; synchronized (this) {policyall () ;}@ Overridepublic void run () {try {while (isStart) {if (msg! = Null) {dos. writeUTF (msg); dos. flush (); msg = null; synchronized (this) {wait (); // after the message is sent, the thread enters the waiting status} dos. close (); // close the output stream and socketif (socket! = Null) socket. close () ;}catch (InterruptedException e) {e. printStackTrace () ;}catch (IOException e) {e. printStackTrace ();}}}
// Defines the interface for Message processing when a Message is received. public interface MessageListener {public void Message (String msg );}
The main interface is ugly.
"
MainActivity code
Public class MainActivity extends Activity {EditText etMessage; TextView tvSend, tvMessage; SocketThread client; MyHandler myHandler; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); setup ();} public void setup () {etMessage = (EditText) findViewById (R. id. etMessage); tvSend = (TextView) findViewById (R. id. tvSend); tvMessage = (TextView) findViewById (R. id. tvMessage); tvSend. setOnClickListener (onClick); myHandler = new MyHandler (); // initialize client = new SocketThread ("10.21.56.226", 8888, new MessageListener () {// call this method after receiving the Message @ Overridepublic void Message (String msg) {// TODO Auto-generated method stub // tvMessage. append (msg); Bundle bundle = new Bundle (); bundle. putString ("input", msg); Message isMessage = new Message (); isMessage. setData (bundle); // use handler to forward myHandler. sendMessage (isMessage) ;}}); // officially starts the thread client. start ();} OnClickListener onClick = new OnClickListener () {public void onClick (android. view. view v) {String message = etMessage. getText (). toString (); Log. v ("Send message", message); if (client. isStart () {client. sendMsg (message) ;};}; private class MyHandler extends Handler {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubLog. v ("processing received messages", ""); tvMessage. append (msg. getData (). getString ("input "));}}}
The server code mainly uses ServerSocket to listen to a port to connect to the client and send and receive information.
Public class ChatServer {boolean started = false; ServerSocket ss = null; List
Clients = new ArrayList
(); Public static void main (String [] args) {new ChatServer (). start () ;}public void start () {try {// ServerSocket listens to port 8888 ss = new ServerSocket (8888); started = true;} catch (BindException e) {System. out. println ("start .... "); System. out. println ("problematic"); e. printStackTrace (); System. exit (0);} catch (IOException e) {e. printStackTrace ();} try {while (started) {Socket s = ss. accept (); Client c = new Cli Ent (s); System. out. println ("a client connected! "); New Thread (c ). start (); clients. add (c); // dis. close () ;}} catch (IOException e) {e. printStackTrace ();} finally {try {ss. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} class Client implements Runnable {private Socket s; private DataInputStream dis = null; private DataOutputStream dos = null; private boolean bConnected = false; public Client (Socket s) {t His. s = s; try {dis = new DataInputStream (s. getInputStream (); dos = new DataOutputStream (s. getOutputStream (); bConnected = true;} catch (IOException e) {e. printStackTrace () ;}} public void send (String str) {try {dos. writeUTF (str);} catch (IOException e) {clients. remove (this); System. out. println ("close a connection"); // e. printStackTrace () ;}} public void run () {try {while (bConnected) {String str = dis. read UTF (); System. out. println (str); for (int I = 0; I <clients. size (); I ++) {Client c = clients. get (I); c. send (str); // System. out. println ("a string send! ");}/** For (Iterator
It = clients. iterator (); * it. hasNext ();) {Client c = it. next (); c. send (str);} * // ** Iterator
It = clients. iterator (); * while (it. hasNext () {Client c = it. next (); c. send (str); *} */} catch (EOFException e) {System. out. println ("Client closed! ");} Catch (IOException e) {e. printStackTrace ();} finally {try {System. out. println (" close All! "); If (dis! = Null) dis. close (); if (dos! = Null) dos. close (); if (s! = Null) {s. close (); // s = null ;}} catch (IOException e1) {e1.printStackTrace ();}}}}}
Next, run the server code, and then the mobile phone end. Multiple Mobile phones can send messages to each other.
Write UDP later