A chat room is required to receive and send messages at the same time.
The following code uses two threads to process the sending and receiving of information. The transmission of information over the Internet uses the UDP protocol. This method does not need to establish a connection, so it is more efficient, but is due to Yongji where the connection, so there will be packet loss of security.
ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;//Chat Room class Public classTalkingroom { Public Static voidMain (string[] args)throwsException {datagramsocket Sendds=NewDatagramsocket (); Datagramsocket receiveds=NewDatagramsocket (10001); //two threads, which are send and receive threads, respectively NewThread (NewSend (Sendds)). Start (); NewThread (Newrecieve (receiveds)). Start (); }}//Send ClassclassSendImplementsrunnable{datagramsocket ds; PublicSend (datagramsocket ds) { This. ds=ds; } Public voidrun () {//read in rows from the keyboardBufferedReader br=NewBufferedReader (NewInputStreamReader (system.in)); String Line=NULL; Try { while((Line=br.readline ())! =NULL) { byte[] buf=line.getbytes (); Datagrampacket DP=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.0.255"), 10001); Ds.send (DP); if(Line.equals ("Over")) Break; } } Catch(Exception e) {} ds.close (); }}//Receive ClassclassRecieveImplementsrunnable{datagramsocket ds; Publicrecieve (Datagramsocket ds) { This. ds=ds; } Public voidrun () { while(true) { byte[] buf=New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); Try{ds.receive (DP); } Catch(Exception e) {} String IP=dp.getaddress (). gethostaddress (); String text=NewString (Dp.getdata (), 0, Dp.getlength ()); if(Text.equals ("Over")) System.out.print ("The other side has gone offline"); ElseSystem.out.println (IP+":"+text); } }}
UDP chat Room Java