1 PackageCom.yyq;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.InputStream;5 ImportJava.io.InputStreamReader;6 ImportJava.net.DatagramPacket;7 ImportJava.net.DatagramSocket;8 Importjava.net.InetAddress;9 Importjava.net.SocketException;Ten One /* A * Write a chat program. There is part of the data, there is the part that sends the data, these two parts need to execute simultaneously - * Then you need to use multithreaded technology. A thread is Cheng, a line is closed. - * Because the receiving and sending action is inconsistent, so the */ - classSendImplementsrunnable{ - Privatedatagramsocket ds; - PublicSend (datagramsocket ds) { + This. ds =ds; - } + Public voidrun () { A Try{ atBufferedReader BUFR =NewBufferedReader (NewInputStreamReader (system.in)); -String line =NULL; - while(line = Bufr.readline ())! =NULL){ - if("88". Equals (line)) { - Break; - } in Else{ - byte[] buf =New byte[1024]; toDatagrampacket DP =NewDatagrampacket (Buf,buf.length,inetaddress.getlocalhost (), 1237); + Ds.send (DP); - } the } * } $ Catch(Exception e) {Panax Notoginseng Throw NewRuntimeException ("Send Side failed!! "); - } the } + } A classReceImplementsrunnable{ the Privatedatagramsocket ds; + Publicrece (datagramsocket ds) { - This. ds =ds; $ } $ Public voidrun () { - Try{ - while(true){ the byte[] buf =New byte[1024]; -Datagrampacket DP =NewDatagrampacket (buf,buf.length);Wuyi Ds.receive (DP); theString IP =dp.getaddress (). gethostaddress (); -String data =NewString (Dp.getdata (), 0, Dp.getlength ()); WuSystem.out.println (ip+data); - } About } $ Catch(Exception e) { - Throw NewRuntimeException ("The Receiving end fails!! "); - } - } A } + Public classChatdemo { the Public Static voidMain (string[] args)throwsSocketException { -Datagramsocket Sendsocket =NewDatagramsocket (); $Datagramsocket Recesocket =NewDatagramsocket (1237); the NewThread (Newrece (Sendsocket)). Start (); the NewThread (NewSend (Sendsocket)). Start (); the } the}
Network Programming-UDP Program Chat applet