Java Socket Long Connection code implementation

Source: Internet
Author: User
Tags gettext

Server-side programs:

Import Java.io.*;import Java.net.*;import java.util.*;PublicClassChatserver {boolean started =False ServerSocket SS =Null list<client> clients =New Arraylist<client> ();PublicStaticvoidMainstring[] (args) {New Chatserver (). Start ();}PublicvoidStart) {Try {ss =New ServerSocket (8888); started =True System.Out.println ("port is on, occupy 8888 port number ...");Catch (bindexception E) {System.Out.println ("port in use ...."); System.Out.println ("please shut down the program and re-run the server!" "); System.exit (0);}Catch (ioexception e) {e.printstacktrace ();}try {While (started) {Socket s = ss.accept (); Client C =New Client (s); System.Out.println ("a Client connected!");New Thread (c). start (); clients.Add (c);}}Catch (ioexception e) {e.printstacktrace ();}finally {Try {ss.close ();}Catch (ioexception e) {e.printstacktrace ();}}}ClassClientImplementsRunnable {Private Socket s;Private DataInputStream dis =NullPrivate DataOutputStream dos =NullPrivate Boolean bconnected =FalsePublicClient (Socket S) {THIS.S = s;Try {dis =New DataInputStream (s.getinputstream ());d OS =New DataOutputStream (s.getoutputstream ()); bconnected =true;}Catch (ioexception e) {e.printstacktrace ();}}PublicvoidSendString Str) {Try {dos.writeutf (str);}Catch (ioexception E) {clients.Removethis); System.Out.println ("the Other Side withdrew!" I removed it from the list! ");}}PublicvoidRun) {try {While (bconnected) {String str = Dis.readutf (); System.Out.println ( "------------from local server:" + str); for (int i = 0; i < clients.size () ; I++) {Client C = Clients. Get (i); c.send (str);}}} catch (eofexception e) {system. Out.println ( "Client closed!");} catch (ioexception e) {e.printstacktrace ();} finally {try {if (dis! = null) dis.close (); if (dos! = null) dos.close ();  If (s! = null) {s.close ();}} catch (ioexception e1) {e1.printstacktrace ();}}}}       

Client Program:

Import java.awt.*;Import java.awt.event.*;Import java.io.*;Import java.net.*;/** *@author Michael Huang * * * *PublicClassChatClientExtendsFrame {Socket s =Null;dataoutputstream dos =Null;datainputstream dis =NullPrivateBoolean bconnected =False TextField Tftxt =New TextField (); TextArea tacontent =New TextArea (); Thread TRECV =New Thread (New Recvthread ());PublicStaticvoidMain(string[] Args) {New ChatClient (). Launchframe (8888);}PublicvoidLaunchframe(int Port) {setlocation (400,300);This.setsize (300,Add (tftxt, borderlayout.south), Add (tacontent, borderlayout.north);p ack ();This.addwindowlistener (New Windowadapter () {@OverridePublicvoidWindowclosing(windowevent Arg0) {disconnect (); System.exit (0);}); Tftxt.addactionlistener (New Tflistener ()); setvisible (true); Connect (port); Trecv.start ();}PublicvoidConnect(int Port) {Try {s =New Socket ("127.0.0.1", port);d OS =New DataOutputStream (s.getoutputstream ());d is =New DataInputStream (s.getinputstream ()); System.out.println ("~~~~~~~~ Connection Successful ~~~~~~~~!"); bconnected =true;}Catch (unknownhostexception e) {e.printstacktrace ();}Catch (ioexception e) {e.printstacktrace ();}}PublicvoidDisconnect() {Try {dos.close ();d is.close (); s.close ();}Catch (ioexception e) {e.printstacktrace ();}}PrivateClassTflistenerImplementsActionListener {PublicvoidActionperformed(actionevent E) {String str = tftxt.gettext (). trim (); tftxt.settext ("");Try {dos.writeutf (str);d Os.flush ();}Catch (ioexception e1) {e1.printstacktrace ();}}}private class recvthread implements Runnable { Span class= "hljs-function" >public void run () {try { while (bconnected) {String str = dis.readutf (); tacontent.settext (tacontent.gettext () + str + catch (socketexception e) {System.out.println ( "exited, bye!"); Span class= "hljs-keyword" >catch (eofexception e) {System.out.println ( "exited, bye!");} catch (ioexception e) {e.printstacktrace ();}}}        

Java Socket Long Connection code implementation

Related Article

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.