Java Socket chat demo

Source: Internet
Author: User

I need to learn about socket recently, so I just ran a chat demo.

Basically, I copied someone else. I added an util class and optimized it.

If you have a swing interface, students and beginners can take it away.

Http://download.csdn.net/detail/sysmaid/3880649

Paste some code.

Server thread:

/*** Service Thread class ** @ author jinghui ** create by 1:38:10 */class serverthread extends thread {private Socket socket; Public serverthread (Socket socket) {This. socket = socket;} public void run () {try {objectinputstream OIS = new objectinputstream (socket. getinputstream (); While (true) {vector v = NULL; try {v = (vector) Ois. readobject ();} catch (exception e) {e. printstacktrace (); system. out. println ("====== = An error occurred while communicating with the client ====== ");} If (V! = NULL & v. size ()> 0) {for (INT I = 0; I <v. size (); I ++) {string info = (string) v. get (I); string key = ""; if (info. startswith (chatutil. msg_login) {key = info. substring (7); // obtain the user name map. put (Key, socket); // Add the client to the list ta_info.append (Key + "login... \ n "); set <string> set = map. keyset (); iterator <string> it = set. iterator (); While (it. hasnext () {// iterative map, send the login information string recivekey = it to all clients. next (); // indicates the key for receiving information, that is, the user name socket S = Map. get (recivekey); printwriter PW = new printwriter (S. getoutputstream (), true); PW. println (Info); PW. flush () ;}} else if (info. startswith (chatutil. msg_exit) {// exit key = info. substring (6); // get the keyois. close (); socket. close (); map. remove (key); set <string> set = map. keyset (); iterator <string> it = set. iterator (); While (it. hasnext () {string recivekey = it. next (); socket S = map. get (recivekey); printwriter pw = New printwriter (S. getoutputstream (), true); PW. println (Info); PW. flush ();} ta_info.append (Key + "exit... \ n "); return; // exit thread} else if (info. startswith (chatutil. msg_userlist) {// transmits the current online user list string userlist = ""; set <string> set = map. keyset (); iterator <string> it = set. iterator (); While (it. hasnext () {key = it. next (); userlist + = Key + "," ;}key = info. substring (10); iterator <string> it2 = set. iterator (); While (It2.hasnext () {string recivekey = it2.next (); If (key. equals (recivekey) {socket S = map. get (recivekey); printwriter PW = new printwriter (S. getoutputstream (), true); PW. println (chatutil. msg_userlist + userlist); PW. flush () ;}} else {// normal message forwarding string [] Infos = chatutil. formatinfos (Info); set <string> set = map. keyset (); iterator <string> it = set. iterator (); While (it. hasnext () {string recivekey = it. next (); If (Re Civekey. equals (Infos [1]) {// find the receiver socket S = map. get (recivekey); printwriter PW = new printwriter (S. getoutputstream (), true); PW. println (Info); // forward the original text, and the client processes PW. flush () ;}}// end else} // end for} // end if v} // end while} catch (exception e) {e. printstacktrace (); ta_info.append (socket + "Exit exception. \ N ") ;}}// end class serverthread

Client Interface:

/*** Constructor * initialization interface in constructor */Public chatclientframe () {super (); this. settitle ("Rabbit chat room client"); this. setbounds (100,100,385,288); Final jpanel = new jpanel (); this. getcontentpane (). add (panel, borderlayout. south); Final jlabel label = new jlabel (); label. settext ("enter chat content"); panel. add (Label); tf_send = new jtextfield (); tf_send.addactionlistener (New actionlistener () {public void actionreceivmed (actionevent arg0) {Send (); // call the sending method}); tf_send.setpreferredsize (new dimension (180, 25); panel. add (tf_send); // message sending region final jbutton button = new jbutton (); button. settext ("send"); button. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {send () ;}}); panel. add (button); // Add send button final jsplitpane splitpane = new jsplitpane (); splitpane. setdividerlocation (100); // the location of the separator bar this. getcontentpane (). add (split Pane, borderlayout. center); Final jscrollpane scrollpane = new jscrollpane (); splitpane. setrightcomponent (scrollpane); ta_info = new jtextarea (); ta_info.setfont (new font ("", Font. bold, 14); scrollpane. setviewportview (ta_info); // information display area // ------- Display User List start ------- final jscrollpane scrollpane1 = new jscrollpane (); userlist = new jlist (); userlist. setmodel (New defaultcomboboxmodel (New String [] {""}); scrol Lpane1.setviewportview (userlist); splitpane. setleftcomponent (scrollpane1); // ------- display the user list end ------- // ------- display the user logon start ------- final jpanel panel_1 = new jpanel (); Final jlabel label_1 = new jlabel (); label_1.settext ("User name:"); panel_1.add (label_1); tf_newuser = new jtextfield (); partition (new dimension (140, 25); panel_1.add (tf_newuser ); final jbutton button_1 = new jbutton (); button_1.s Ettext ("login"); button_1.addactionlistener (New actionlistener () {public void actionreceivmed (actionevent arg0) {// perform the login operation if (loginflag) {joptionpane. showconfirmdialog (null, "the current user has logged on"); return;} string username = tf_newuser.gettext (). trim (); vector <string> V = new vector <string> (); V. add (chatutil. fittingloginmsg (username); // send the logon information try {out. writeobject (V); // send out. flush ();} catch (exception e) {e. printstacktrace () ;} Tf_newuser.setenabled (false); // the user name cannot be changed to button_1.setvisible (false); // The logon button hides loginflag = true; getonlineuser (username ); // get online user list}); panel_1.add (button_1); Final jbutton button_2 = new jbutton (); button_2.settext ("return"); button_2.addactionlistener (New actionlistener () {public void actionreceivmed (actionevent arg0) {If (! Loginflag) {// joptionpane. showmessagedialog (null, "logged out or not logged in! "); Return;} string exituser = tf_newuser.gettext (). trim (); vector <string> V = new vector <string> (); V. add (chatutil. fittingexitmsg (exituser); // exit information try {out. writeobject (V); out. flush ();} catch (exception e) {e. printstacktrace ();} system. exit (0) ;}}); panel_1.add (button_2); this. getcontentpane (). add (panel_1, borderlayout. north); // ------- display the user logon end ------- // ------- System Tray start ------- if (systemtray. issupported () {URL url = chatclientframe. class. getresource (chatutil. logo_image); imageicon I _con = new imageicon (URL); image = I _con.getimage (); trayicon = new trayicon (image); trayicon. addmouselistener (New mouseadapter () {public void mouseclicked (mouseevent e) {If (E. getclickcount () = 2) {showframe (); // display interface }}); trayicon. settooltip ("Rabbit chat"); popupmenu = new popupmenu (); menuitem exitmenu = new menuitem ("quit"); exitmenu. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent arg0) {string exituser = tf_newuser.gettext (). trim (); vector <string> V = new vector <string> (); V. add (chatutil. fittingexitmsg (exituser); // exit information try {out. writeobject (V); out. flush (); out. close (); socket. close ();} catch (exception e) {e. printstacktrace ();} system. exit (0) ;}}); popupmenu. add (exitmenu); trayicon. setpopupmenu (popupmenu); systemtray = systemtray. getsystemtray (); try {systemtray. add (trayicon);} catch (exception E1) {e1.printstacktrace () ;}// ------- System Tray end -------}

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.