Reprint Please specify the Source: http://blog.csdn.net/u012975705/article/details/48752377
App source download address: https://github.com/noyo/ Chatroom/tree/master
Server-side code download address: http://download.csdn.net/detail/u012975705/9141251 Socket Introduction
Two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket. The socket is typically used to implement a connection between the client and the service party. The socket is a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.
Server-side Listen (listening) whether a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept (accepted) message to the client side. A connection is established. Both the server end and the client side can communicate with each other by means of send,write.
For a full-featured socket, include the following basic structure, its work process contains the following four basic steps: 1, create socket;2, open the input/output connection to the socket, 3, according to a certain protocol for the socket read/write operation; 4, close the socket.
Java provides two classes of sockets and ServerSocket in Package java.net, respectively, to represent two-way connected clients and services. This is one of two very good packaged classes and is easy to use.
Socket client = new socket ("127.0.0.1", 80);//The first parameter is the host IP, the second parameter is the port number
ServerSocket Server = new ServerSocket (80);
Note that you must be careful when choosing a port. Each port provides a specific service, and only the correct port is given to obtain the appropriate service. The port number for the 0~1023 is reserved for the system, for example, the port number of the HTTP service is the port number of the 80,telnet service is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs when the socket is created, a ioexception is generated and must be processed in the program. So in creating a socket or serversocket you have to catch or throw an exception. Chat Room Writing
Directly on the code, most parts of the code have comments, what you do not know where to ask in the comments.
1. Client code
ChatClient.java:package Com.practice.noyet.chatroom.socket;
Import Android.util.Log;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.Socket;
/** * Created by Noyet on 2015/9/26.
* * Public class ChatClient {public socket socket;
/** data is written to the server side/public printwriter writer;
/** read data from the server/public BufferedReader reader;
Public ChatClient () {createsocket ();
/** * Get chatclient instance * @return chatclient * * Public synchronized chatclient getchatclient () {
return new ChatClient (); /** * Create socket */public void Createsocket () {try {/** initialize socket, parameter: Host IP (server host I
p) Port number */socket = new Socket ("192.168.1.142", 1314);
/** initialization Write Data flow * * writer = new PrintWriter (Socket.getoutputstream ()); /** initialization Read Data stream * * reader = new BufferedReader (New inPutstreamreader (Socket.getinputstream ()));
catch (Exception e) {/** PRINT error message * * PRINTERRORINFO ("Chatclient.createsocket", e);
E.printstacktrace ();
}/** * Send message to server * @param chatmsg information content/public void sendchatmsg (String chatmsg) {
/** writes the data to the server-side/writer.println (CHATMSG);
/** flushes the output stream (writes to the server) so that the server immediately receives the string/Writer.flush (); /** * Get data returned from server * @return string/public string getchatmsg () {try {Str
ing str = reader.readline ();
return str;
catch (Exception e) {/** PRINT error message * * PRINTERRORINFO ("chatclient.getchatmsg", e);
E.printstacktrace ();
return null;
/** * Close IO stream/public void Destroysocket () {try {if (reader!= null) {
Reader.close ();
} if (writer!= null) { Writer.close ();
} if (socket!= null) {socket.close ();
The catch (IOException e) {/** print error message/printerrorinfo ("Chatclient.destroysocket", e);
E.printstacktrace (); }/** * Print error message * @param tag generates an error message * @param info error message/private void Printerrorinfo (String tag, Exception info)
{LOG.D (tag + "error", "Error:" + info);
}
}
2, app main activity code
MainActivity.java:package Com.practice.noyet.chatroom;
Import Android.os.AsyncTask;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.ArrayAdapter;
Import Android.widget.ListView;
Import Android.widget.TextView;
Import com.practice.noyet.chatroom.socket.ChatClient;
Import java.util.ArrayList;
Import java.util.List; public class Mainactivity extends Appcompatactivity implements View.onclicklistener {/** data entry box for client A with clear flags */PRI
Vate Clearedittext acontent;
/** Client A's data submission button */private TextView aSend;
/** The Data entry box for Client B with clear flag */private Clearedittext bcontent;
/** Client B's Data submission button * * Private TextView bsend;
/** displays data returned from the server/private ListView Mlistview;
/** User A's client * * Private chatclient Clienta;
/** User B's Client * * Private chatclient CLIENTB;
Private arrayadapter<string> Madapter;
Private list<string> List; @Override protected void OncreatE (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Initview ();
InitData ();
Initevent ();
/** * Initialize control/private void Initview () {new Myasynctask (). Execute (1);
Acontent = (clearedittext) Findviewbyid (R.ID.A_CLIENT_CET);
ASend = (TextView) Findviewbyid (r.id.a_client_send);
bcontent = (clearedittext) Findviewbyid (R.ID.B_CLIENT_CET);
Bsend = (TextView) Findviewbyid (r.id.b_client_send);
Mlistview = (ListView) Findviewbyid (R.id.chat_content_listview);
}/** * Initialization data */private void InitData () {list = new arraylist<> (); Madapter = new Arrayadapter<> (this, Android.
R.layout.simple_list_item_1, list);
Mlistview.setadapter (Madapter);
/** * Initialize the listening event/private void Initevent () {Asend.setonclicklistener (this); Bsend.setonclicklisteneR (this);
@Override public void OnClick (view view) {switch (View.getid ()) {case R.id.a_client_send:
Sends a message to the server clienta.sendchatmsg (Acontent.gettext (). toString ());
Gets the data returned from the server, New Myasynctask (). Execute (2);
Break
Case R.id.b_client_send://Send Message to Server clientb.sendchatmsg (Bcontent.gettext (). toString ());
Gets the data returned from the server, New Myasynctask (). Execute (3);
Break
}} @Override protected void OnDestroy () {Super.ondestroy ();
Clienta.destroysocket ();
Clientb.destroysocket (); Private class Myasynctask extends Asynctask<integer, Integer, integer> {@Override protected Integer doinbackground (integer ... integers) {if (integers[0] = = 1) {Clienta = new Chatclien
T (); CLIENTB = new ChatClient ();
else if (integers[0] = = 2) {list.add ("Client A:" + clienta.getchatmsg ());
else if (integers[0] = = 3) {list.add ("Client B:" + clienta.getchatmsg ());
return integers[0];
} @Override protected void OnPostExecute (Integer integer) {super.onpostexecute (integer);
if (integer = = 2 | | integer = = 3) {madapter.notifydatasetchanged ();
}
}
}
}
3, custom EditText code with the purge button
ClearEditText.java:package Com.practice.noyet.chatroom;
Import Android.content.Context;
Import android.graphics.drawable.Drawable;
Import android.text.Editable;
Import Android.text.TextWatcher;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.view.View.OnFocusChangeListener;
Import android.view.animation.Animation;
Import Android.view.animation.CycleInterpolator;
Import android.view.animation.TranslateAnimation;
Import Android.widget.EditText;
public class Clearedittext extends EditText implements Onfocuschangelistener, Textwatcher {/** * Delete button Reference * *
Private drawable mcleardrawable;
Public Clearedittext {This (context, NULL); The public clearedittext (context context, AttributeSet Attrs) {/** The construction method is also very important, without this many attributes can not be defined in the XML */th Is (context, Attrs, Android.)
R.attr.edittextstyle); Public Clearedittext, AttributeSet attrs, int defstyLe) {Super (context, attrs, Defstyle);
Init (); private void Init () {/** get edittext drawableright, if not set we use the default picture * * mcleardrawable = Getcompoun
Ddrawables () [2]; if (mcleardrawable = = null) {mcleardrawable = Getresources (). getdrawable (R.drawable.del)
;
Mcleardrawable.setbounds (0, 0, mcleardrawable.getintrinsicwidth (), Mcleardrawable.getintrinsicheight ());
Setcleariconvisible (FALSE);
Setonfocuschangelistener (this);
Addtextchangedlistener (this);
/** * Because we can not set the Click event directly to EditText, so we use to remember the position we pressed to simulate the click event * when we press the position at the edittext width-the icon to the right of the control spacing-the width of the icon and * EditText Width-The distance between the icon and the right side of the control we clicked the icon, the vertical direction did not consider * * @Override public boolean ontouchevent (Motionevent event)
{if (Getcompounddrawables () [2]!= null) {if (event.getaction () = = motionevent.action_up) { Boolean touchable = Event.getx () > (getwidth()-Getpaddingright ()-mcleardrawable.getintrinsicwidth ()) && (E
Vent.getx () < ((GetWidth ()-getpaddingright ()));
if (touchable) {This.settext ("");
/** Shaking Animation * * Setshakeanimation ();
}} return Super.ontouchevent (event); /** * When Clearedittext focus changes, judge inside string length set clear icon display and hide */@Override public void Onfocuschange (View V
, Boolean Hasfocus) {if (Hasfocus) {setcleariconvisible (GetText (). Length () > 0);
else {setcleariconvisible (false); }/** * Set clear icon display and hide, call setcompounddrawables for EditText to draw up * @param visible Delete button See * * * Protec
Ted void Setcleariconvisible (Boolean visible) {drawable right = visible? Mcleardrawable:null;
Setcompounddrawables (Getcompounddrawables () [0], Getcompounddrawables () [1], right, Getcompounddrawables () [3]); /** * The method of callback when the contents of the input box is changed * * @Override public void ontextchanged (charsequence s, int start, int
Count, int after) {setcleariconvisible (s.length () > 0);
@Override public void beforetextchanged (charsequence s, int start, int count,
int after) {} @Override public void aftertextchanged (Editable s) {}/** * Set shaking animation * *
public void Setshakeanimation () {this.setanimation (Shakeanimation (5)); /** * Shaking animation * @param counts 1 seconds to shake how many under * @return Animation/public static Animation Shakean
Imation (int counts) {Animation translateanimation = new Translateanimation (0, 10, 0, 0);
Translateanimation.setinterpolator (New Cycleinterpolator (counts));
Translateanimation.setduration (1000); return translateanimation;
}
}
4, Interface layout
Activity_main.xml: <relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= " Http://schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "and
roid:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" Tools:context= ".
Mainactivity "> <linearlayout android:id=" @+id/aclient "android:gravity=" center_vertical " android:orientation= "Horizontal" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" "> <textview android:text=" Client A "android:textsize=" 16SP "Android:layout_ weight= "2" android:layout_width= "0DP" android:layout_height= "Wrap_content"/> <com. Practice.noyet.chatroom.Clearedittext android:id= "@+id/a_client_cet" android:paddingleft= "15DP" Android:textsi
Ze= "16sp" android:singleline= "true" android:textcolorhint= "@android: Color/darker_gray"
Android:hint= "Please enter the string to be passed into the server" android:background= "@drawable/input" android:layout_weight= "6" Android:layout_width= "0DP" android:layout_height= "30DP"/> <textview Android : id= "@+id/a_client_send" android:paddingleft= "5DP" android:text= "Send" android:textsize= "16sp" android:layout_weight= "1" android:layout_width= "0DP" android:layout_height= "Wra P_content "/> </LinearLayout> <linearlayout android:id=" @+id/bclient "Android:layout" _margintop= "10DP" android:layout_below= "@id/aclient" android:gravity= "center_vertical" Android:ori
entation= "Horizontal" Android:layout_width= "Match_parent" android:layout_height= "wrap_content" > <textview android:text= "Client B" android:textsize= "16SP" android:layout_weight= "2" android:layout
_width= "0DP" android:layout_height= "wrap_content"/> <com.practice.noyet.chatroom.clearedittext
Android:id= "@+id/b_client_cet" android:paddingleft= "15DP" android:textsize= "16SP" Android:singleline= "true" android:textcolorhint= "@android: Color/darker_gray" Android:hint = "Enter the string to be passed into the server" android:background= "@drawable/input" android:layout_weight= "6" Androi D:layout_width= "0DP" android:layout_height= "30DP"/> <textview android:id= "@+id/b_c"
Lient_send "android:paddingleft=" "5DP" android:text= "send" android:textsize= "16SP" Android:layout_weight= "1" android:layout_width= "0DP" android:layout_height= "wrap_content"/> </linearlayo ut> <linearlayout android:layout_margintop= "15DP" android:layout_below= "@id/bclient" Droid:layout_width= "Match_parent" android:layout_height= "match_parent" > <listview Andro id:background= "@drawable/content" android:id= "@+id/chat_content_listview" android:dividerheight= "1 DP "android:divider=" @android: Color/white "android:layout_width=" Match_parent "Android" : layout_height= "Match_parent"/>