UDP Server Interface Monitoring

Source: Internet
Author: User
Tags try catch

Today in the project, found that the different subnets are not able to do UDP communication, do not know if this is the case

An error has been encountered: Eclipse is experiencing errors:

The type JPEGImageEncoder isn't accessible due to restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar

Google finds it resolved in the following ways:

This is an issue with eclipse settings, which by default set these access-restricted APIs as error
Windows-preferences-java-complicer-errors/warnings
Forbidden References (access rules) in the deprecated and restricted API is selected as warning to compile and pass .

Java UDP Server code:

 PackageGUI;Importjava.awt.*;Importjava.awt.event.*;ImportJava.io.*;ImportJava.util.Scanner;Importjavax.swing.*;ImportJavax.swing.border.Border;ImportJavax.swing.border.LineBorder;////Importjava.io.IOException;ImportJava.net.DatagramSocket;ImportJava.net.DatagramPacket;Importjava.net.InetAddress; Public classGuihelloextendsJFrameImplementsActionListener {Private StaticJLabel label =NewJLabel ("192.168.0.3:8888"); Private StaticJTextArea Ta=NewJTextArea (30,80); PrivateJFileChooser jfc=NewJFileChooser (NewFile (".")); PrivateJButton Bopen,bsave; PrivateJButton Blisten,bok;  PublicGuihello () {Super("UDP Monitor GUI"); JScrollPane PS=NewJScrollPane (TA); Bopen=NewJButton ("Select Source file"); Bsave=NewJButton ("Save Variable"); Blisten=NewJButton ("Start monitoring");//This is a custom button.BOk =NewJButton ("Test button"); //Custom Two JPanelJPanel Panel1 =NewJPanel (NewBorderLayout ()); JPanel Panel2=NewJPanel (NewBorderLayout ()); //Two panel a second background is redPanel2.setbackground (color.red);         Panel1.add (Blisten, Borderlayout.center);         Add (Panel1);         Panel2.add (label, Borderlayout.east);                  Add (Panel2); SetLayout (NewFlowLayout (flowlayout.center,10,15)); //Add (label);Add (PS);         Add (bopen);        Add (bsave); //Add (blisten);Add (bOk); Border b=NewLineborder (Color.orange, 2);         Blisten.setborder (b); Bopen.addactionlistener ( This); Bsave.addactionlistener ( This); Blisten.addactionlistener ( This); Bok.addactionlistener ( This); SetVisible (true); SetSize (1600,1500); }     Public Static voidMain (string[] args) {//TODO auto-generated Method StubGuihello frm=NewGuihello ();        Frm.setdefaultcloseoperation (Jframe.exit_on_close); }         Public voidactionperformed (ActionEvent e) {JButton JBT=(JButton) E.getsource (); if(jbt==bopen) {            intStatus=jfc.showopendialog ( This); if(status!=jfilechooser.approve_option) Ta.settext ("No Files selected"); Else {                Try{File file1=Jfc.getselectedfile (); Scanner Scan=NewScanner (FILE1); String Info="";  while(Scan.hasnext ()) {String str=Scan.nextline (); Info+=str+ "\ r \ n";                    } scan.close ();                Ta.settext (info); }                Catch(FileNotFoundException ex) {} }}Else if(jbt==bsave)                 {Save (); }Else if(jbt==Blisten) {                    //The listener function must be plus try CatchRunnable TR =NewRunnable () { Public voidrun () {Try{Listen (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();           }               }           };                  Javax.swing.SwingUtilities.invokeLater (TR); }Else{Ta.settext ("Server is turned on");                  Test (); }         }        //each button corresponds to a function    Private Static voidSave () {Ta.settext ("Saved Buttons"); }    Private Static voidListen ()throwsioexception{//1. Create datagramsocket; indicate server portDatagramsocket Server =NewDatagramsocket (8888); byte[] Recvbuf =New byte[1024]; //2. Create a packet to receive the content. Datagrampacket Recvpacket=NewDatagrampacket (Recvbuf, recvbuf.length); //3. Receive Dataserver.receive (Recvpacket); //System.out.println (Packet.getdata (). toString ()); //The above statement prints a message error because GetData () returns byte[] type data, and the direct ToString serializes it instead of extracting the character. You should use the following methods:String Recvstr =NewString (Recvpacket.getdata (), 0, Recvpacket.getlength ()); System.out.println ("Hello world!" +recvstr); intPort =Recvpacket.getport (); //address is inetaddress type: (used for postback)InetAddress InetAddr =recvpacket.getaddress (); //the address is a string type:String stradd =recvpacket.getaddress (). gethostaddress (); Ta.settext ("Listen \ n to client address:" \ +stradd+ "\ n port:" +port+ "\ n Contents:" +recvstr); String Sendstr= "Hello!" I ' m Server "; byte[] sendbuf; SendBuf=sendstr.getbytes (); Datagrampacket Sendpacket=NewDatagrampacket (SendBuf, Sendbuf.length, InetAddr, Port);   Server.send (Sendpacket); //4, close the connection. Server.close (); }    Private Static voidTest () {Ta.settext ("Test button: BOk"); }}

Java Client code:

 Packagesocket;/*The UDP client UDP client first sends a data message to the server that is passively waiting to be contacted. A typical UDP client performs the following three main steps: 1. Create a Datagramsocket instance and optionally set the local address and port number. 2. Use the Send () method of the Datagramsocket class and the receive () method to send and accept datagrampacket instances for communication. 3. After the communication is complete, use the close () method of the Datagramsocket class to destroy the socket. The Connect () method of the Datagramsocket class does allow you to specify a remote address and port, but the feature is optional. */    ImportJava.net.DatagramSocket; Importjava.net.InetAddress; ImportJava.net.DatagramPacket;  Public classudpsendtest{ Public Static voidMain (string[] args)throwsexception{//1. Create datagramsocket for UDP data transfer. //datagramsocket socket = new Datagramsocket ();//Native Address (default), any available port//the native address (the disadvantage is that you must know and must be a local IP address), specify the native port our address and portDatagramsocket socket =NewDatagramsocket (4567, Inetaddress.getbyname ("192.168.1.103")); //2. Create a packet to send            byte[] buf = "Harry Potter's Deathly Hallows, Long I. is 2 of the 222 without snow". GetBytes (); //opposite address and port 192.168.0.3Datagrampacket packet =NewDatagrampacket (buf, Buf.length, Inetaddress.getbyname ("192.168.1.103"), 8888); //3. Sendsocket.send (packet); //4. Close the connectionSocket.close (); }    }

UDP Server Interface Monitoring

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.