Simple UDP communication Program in Java

Source: Internet
Author: User

Objective
原创文章欢迎转载,请保留出处。若有任何疑问建议,欢迎回复。邮箱:[email protected]

I learn Java socket practiced Hand applet, master please floated, only as a study note, no technical content.

Analysis

Here, two separate threads are used for the package and packet collection, and two classes are designed to implement the Runnable interface, which communicates with the main form of the pipeline.

Code

mainfest.txt file : Note here there are myqq. Carriage return after myqq and space before Myqq.myqq

Main-Classmyqq.MyQQ

Myqq.java file :

Package Myqq;import Java.awt.*;import java.awt.Event. *;import Java.io.*;import Java.net.*;class Udpsend implements runnable{PrivateDatagramsocket ds;PrivateInputStream is; Public Udpsend(Datagramsocket Ds,inputstream is)    {Try{ This. ds = ds; This. is= is; }Catch(Exception e) {Throw NewRuntimeException ("Send side Error"); }    } Public void Run()    {Try{//Read data from a text boxBufferedReader br =NewBufferedReader (NewInputStreamReader ( is)); String s =NULL; while((S=br.readline ())! =NULL)            {//Stop sending data when you enter 886                if("886". Equals (s)) Break;byte[] buf = S.getbytes ();//This is the destination IP and port to send the packet, or it can be set to broadcast addressDatagrampacket DP =NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("169.254.255.255"),12345);            Ds.send (DP);            } br.close ();        Ds.close (); }Catch(Exception e) {Throw NewRuntimeException ("Send side Error"); }}}class Udprecv implements runnable{PrivateDatagramsocket ds;PrivateOutputStream is; Public Udprecv(Datagramsocket Ds,outputstream is)    {Try{ This. ds = ds; This. is= is; }Catch(Exception e) {Throw NewRuntimeException ("Receive-side error"); }    } Public void Run()    {Try{ while(true)            {//UDP The maximum packet length is 64k                byte[] buf =New byte[1024x768* -]; Datagrampacket DP =NewDatagrampacket (buf,buf.length); Ds.receive (DP);//Get the source IP and data contents of the packetString IP = dp.getaddress (). gethostaddress (); String data =NewString (Dp.getdata (),0, Dp.getlength ()); String s = ip+"::"+data; is. Write (S.getbytes ()); is. Flush (); }           }Catch(Exception e) {Throw NewRuntimeException ("Receive-side error"); }}}class myqq {Private StaticFrame R;Private StaticTextArea Tsend;//Send text box    Private StaticTextArea Trecv;//Receive text box    //Send communication pipeline    Private StaticPipedInputStream sis;Private StaticPipedOutputStream SOS;//Receive communication pipeline    Private StaticPipedInputStream RIS;Private StaticPipedOutputStream Ros; Public Static void Main(string[] args) throws Exception {Datagramsocket Sendds =NewDatagramsocket (); Datagramsocket RECVDS =NewDatagramsocket (12345);//Listening portsSIS =NewPipedInputStream (); SOS =NewPipedOutputStream ();        Sis.connect (SOS); RIS =NewPipedInputStream (); Ros =NewPipedOutputStream (); Ris.connect (ROS);//Start send and receive threads        NewThread (NewUDPRECV (Recvds,ros)). Start ();NewThread (NewUdpsend (sendds,sis)). Start (); System. out. println ("Hello myqwq!"); Init (); while(true)        {byte[] buf =New byte[1024x768];intLen = Ris.read (BUF); Trecv.append (NewString (BUF,0, Len) +"\ r \ n"); }    } Public Static void Init() throws IOException {r =NewFrame ("MYQQ"); TRECV =NewTextArea ("", -, -, textarea.scrollbars_vertical_only); Tsend =NewTextArea ("", -, -, textarea.scrollbars_vertical_only); R.setbounds ( -, -, -, -); R.setlayout (NewFlowLayout ());        R.add (TRECV); R.add (Tsend);//frame Events        Event(); R.setvisible (true);//Set the input box to the current focusTrecv.transferfocus (); } Public Static void Event() {R.addwindowlistener (NewWindowadapter () { Public void windowclosing(WindowEvent e) {System.exit (0);        }        }); Tsend.addkeylistener (NewKeyadapter () { Public void keypressed(KeyEvent e) {if(E.getkeycode () ==keyevent.vk_enter)//Enter to send data{E.consume ();Try{Sos.write (Tsend.gettext () +"\ r \ n"). GetBytes ()); Sos.flush ();//system.out.println (Tsend.gettext ());}Catch(Exception ex) {Throw NewRuntimeException ("IO Error"); } tsend.settext ("");     }            }        }); }}
Compiling and packaging

To the file directory, you can also use the IDE to build the project

javac -d . MyQQ.javajar cvfm myqq.jar mainfest.txt myqq
Run effect

Run the packaged Myqq.jar directly: (because there is only one computer, the address is written in the broadcast address, can receive the proof program successfully sent and received the package)

Simple UDP communication Program in Java

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.