1. Introduction
The socket is essentially Java encapsulating the TCP protocol on the Transport Layer (note: UDP uses the Datagramsocket Class). To implement the socket transfer, you need to build the client and server side. In addition, the transmitted data can be strings and bytes. String transfer is mainly used for simple applications, more complex applications (such as Java and C + + for communication), often need to build their own application layer rules (similar to the Application layer protocol), and the use of bytes to transport.
2. String transfer-based socket case
1) server-side code (console-based application, 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 final in T 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 ("server started ..."); Socket client = null; while (true) {client = Server.accept (); Put the client intoMlist.add (client) in the Clients collection; Mexecutorservice.execute (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) {this.socket = socket; try {in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); The client sends the following information to the client as long as it is in a row to the server. msg = "Server address:" +this.socket.getinetaddress () + "Come Toal:" +mlist.size () + "(server send)"; This.sendmsg (); } catch (IOException e) {e.printstacktrace (); }} @Override public void Run () {try {while (true) {if (msg = In.readline ()) = null) { When the client sends the message: Exit, close the Connect if (Msg.equals ("Exit")) {SYSTEM.OUT.PR Intln ("Ssssssss"); Mlist.remove (socket); In.close (); msg = "User:" + socket.getinetaddress () + "Exit Total:" + mlist.size (); Socket.close (); This.sendmsg (); Break Receives the message sent by the client MSG, and then sends it to the client. } else {msg = socket.getinetaddress () + ":" + msg+ "(server send)"; This.sendmsg (); }}}} catch (Exception e) {e.printstacktRace (); }}/** * Loops through the collection of clients, sending 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 Outputstreamwrite R (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.message;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 = ""; Receive line Cheng send over the message and use TextView to display the 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 that the receiving server sends over the data new thread (Socketdemo.this). Start (); }/** * If there is an exception to the connection, eject alertdialog! */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 (); /** * Reads the information from the server and sends it through handler to the UI thread */public void run () {try {while (true) { if (!socket.isclosed ()) {if (socket).IsConnected ()) {if (!socket.isinputshutdown ()) {if (content = In.read Line ()) = null) {content + = "\ n"; Mhandler.sendmessage (Mhandler.obtainmessage ()); } else {}}}}} catch (Exception e) {e.printstacktrace (); } }}
Analytical:In addition to the Isclose method, the socket class has a isconnected method to determine if the socket object is connected successfully.See this name, perhaps the reader will have a misunderstanding.in fact, the IsConnected method is not judged by the current connection state of the socket object, but whether the socket object has been successfully connected, if the connection is successful, even if Isclose now returns True, IsConnected still returns True. Therefore, to determine whether the current socket object is connected, you must use both the Isclose and IsConnected methods, that is, only if Isclose returns false, IsConnected returns True when the socket object is in a connected state. While most of the time you can close a network connection using the socket class or the Close method of the input output stream, sometimes we just want to turn off OutputStream or InputStream, and while shutting down the input and output stream, the network connection is not turned off. This requires two other methods of the socket class: Shutdowninput and Shutdownoutput, which only close the corresponding input and output streams, and they do not have the ability to turn off the network connection at the same time. like the isclosed, isconnected method, thesocket class also provides two methods to determine whether the input of the socket object, the output stream is closed, and the two methods are Isinputshutdown () and Isoutputshutdown (). Shutdowninput and shutdownoutput do not affect the state of the socket object.
2. Byte-based transmission
When byte-based transmission, it is necessary to convert the corresponding string and integer type to the corresponding network byte for transmission. For more information on how to convert this to a network byte, please refer to the "network collection: byte[of Java integer number and network byte order" array conversion relationship.
An example of an Android socket