Usually chat is in the same window, so, this window at the same time to send data and receive data, then need to implement multi-threading.
Create a class:
Put the sending and receiving end of the chat in the same class, start a window
1 Public classCharroom {2 3 Public Static voidMain (string[] args)throwsIOException {4 5 //creating the socket send and receive objects6Datagramsocket send =NewDatagramsocket ();7Datagramsocket receive =NewDatagramsocket (10010);8 9 //2 simultaneous runs with multiple threadsTenSendthread st =Newsendthread (send); OneReceivethread RT =NewReceivethread (receive); A -Thread Stthread =NewThread (ST); -Thread Rtthread =NewThread (RT); the - //Start Thread - Stthread.start (); - Rtthread.start (); + - +}
Then set up the Send class:
1 Public classSendthreadImplementsRunnable {2 3 //construct a parameter4 Privatedatagramsocket ds;5 6 PublicSendthread (datagramsocket ds) {7 This, D1 =ds;8 }9 Ten Public voidrun () { One A Try { - - //the contents of the keyboard input, data packaging the //Create keyboard input object, IO stream -BufferedReader br =NewBufferedReader (NewInputStreamReader ( - system.in)); - //reading the input data +String line =NULL; - while(line = Br.readline ())! =NULL) { + //Set Exit Criteria A if(Line.endswith ("886")) { at Break; - } - - //string converted to byte, packaged - byte[] Bys =line.getbytes (); - //Send Data inDatagrampacket DP =NewDatagrampacket (bys, Bys.length, -Inetaddress.getbyname ("172.19.xx.xxx"), 10010); to + Ds.send (DP); - the } * //Freeing Resources $ ds.close ();Panax Notoginseng - } the //Handling Exceptions + Catch(IOException e) { A e.printstacktrace (); the } + } -}
Receive side: (To start all the time, so there is no need to release resources)
1 Public classReceivethreadImplementsRunnable {2 3 //Construction Method Receive4 Privatedatagramsocket ds;5 6 PublicReceivethread (datagramsocket ds) {7 This, D1 =ds;8 }9 Ten //Receive Data One Public voidrun () { A - Try { - //The receiving end has been started the while(true) { - //Create a packet - byte[] Bys =New byte[1000]; -Datagrampacket DP =NewDatagrampacket (bys, bys.length); + - //Receiving Packets + Ds.receive (DP); A at //Parsing Packets -String result =NewString (Dp.getdata (), 0, Dp.getlength ()); - //gets the machine name of the sending end -String name =dp.getaddress (). GetHostName (); - - //Print to console inSystem.out.println ("from" + Name + "Send:" +result); - } to } + //Handling Exceptions - Catch(IOException e) { the e.printstacktrace (); * } $ Panax Notoginseng } -}
Based on these, build the GUI, plus optimize, you can make a chat room
Java 25-5 Network Programming Multi-threaded implementation chat room