JAVA--UDP Communication and TCP communication

Source: Internet
Author: User
Tags file copy

IP address and port number

The port number is represented by a two-byte (16-bit binary number) whose value range is 0~65535, where the port number between 0~1023 is used for some well-known network services and applications,

A user's normal application needs to use a port number above 1024 to avoid the port number being consumed by another application or service.

inetaddress

Common methods

Code Demo:

1 public     static void Main (string[] args) throws Unknownhostexception {2         //inetaddress inet= Inetaddress.getlocalhost (); 3         //Host name +IP address 4         inetaddress inet=inetaddress.getbyname ("Desktop-kcd8g34"); 5         System.out.println (inet); 6         String Host=inet.gethostname (); 7         string ip=inet.gethostaddress (); 8         System.out.println (host+ "..." +ip); 9     }
UDP communicationDatagrampacket

datagramsocket

UDP Network Program

Code Demo:

1//Sender 2 public class Udpsend {3 public     static void Main (string[] args) throws IOException {4         //1. Package 5         //clear Data 6         byte[] bytes= "How are You?" GetBytes (); 7         //Clear Destination IP address 8         inetaddress inet=inetaddress.getbyname ("127.0.0.1" ); 9         //pack         of datagrampacket dp=new datagrampacket (bytes, bytes.length,inet,8888);         //2. Create a courier company         Datagramsocket ds=new datagramsocket ();         //3. Send Ds.send         (DP),         //4. Release Resources         Ds.close (); 17     }18 19}
1//Receive Side 2 public class Udpreceive {3 public     static void Main (string[] args) throws IOException {4         //Explicit port number 5         Datagramsocket ds=new Datagramsocket (8888); 6         //create byte array to receive data 7         byte[] Bytes=new byte[1024]; 8         //Create received Packet 9         datagrampacket dp=new datagrampacket ( Bytes, bytes.length);         14//Receive one-by-one         ds.receive (DP);/         /Get data on the receiving packet         int length=dp.getlength ();         String ip=dp.getaddress (). gethostaddress ();         int port=dp.getport ();         System.out.println (" The IP address is: "+ip+" port number is: "+port+" sent the content is: "+new String (Bytes,0,length));         //Release Resources         Ds.close ();     }20 21}
TCP Communication

One is the ServerSocket class, which represents the server side, and one is the socket class, which is used to represent the client.

ServerSocket

Socket

Method declaration

Function description

int Getport ()

This method returns an int type object that is the port number of the socket object and the server-side connection

InetAddress getlocaladdress ()

This method is used to get the local IP address of the socket object binding and to encapsulate the IP address as an object of type inetaddress return

void Close ()

This method is used to close the socket connection and end the communication. All of the input/output streams associated with the socket should be closed before closing the socket because a good program should release all resources at the end of execution

InputStream getInputStream ()

The method returns an input stream object of type InputStream, which is used to read the data sent by the client if the object is returned by the server-side socket, and vice versa, to read the data sent by the server side.

OutputStream Getoutputstream ()

The method returns an output stream object of type OutputStream, which is used to send data to the client if the object is returned by a server-side socket, and vice versa, to send data to the server side

Graphic:

Code Demo:

1//Sender 2 public class Udpsend {3 public     static void Main (string[] args) throws IOException {4         //1. Package 5         //clear Data 6         Scanner sc=new Scanner (system.in); 7         //Clear Destination IP address 8         inetaddress inet=inetaddress.getbyname (" 192.168.1.171 "); 9         //2. Create courier company         Datagramsocket ds=new Datagramsocket (); one while         (true) {             String mes=sc.next (); 13             byte[] bytes=mes.getbytes ()             //pack             datagrampacket dp=new datagrampacket (bytes, bytes.length, inet,6666);             //3. Send the             ds.send (DP), and         //4. Release Resources         //ds.close ();         22     }
1//Receive Side 2 public class Udpreceive {3 public     static void Main (string[] args) throws IOException {4         //Explicit port number 5         Datagramsocket ds=new Datagramsocket (8888); 6         //create byte array to receive data 7         byte[] Bytes=new byte[1024]; 8         //Create received Packet 9 while         (true) {             datagrampacket dp= New Datagrampacket (bytes, bytes.length), one             //Receive             the Ds.receive (DP), and/             /Get data on the receiving packet             int length= Dp.getlength ();//The byte length that is explicitly sent is             String ip=dp.getaddress (). gethostaddress ();             Port=dp.getport (); 17             System.out.println ("IP address:" +ip+ "port number is:" +port+ "sent the content is:"                                             +new String (bytes,0,length));         }20}
1//server-side 2 public class TCPServer {3 public     static void Main (string[] args) throws IOException {4         //create server Socket 5
   serversocket server=new ServerSocket (7777); 6         //Call the Accept method to create a link with the client 7         Socket socket=server.accept (); 8         InputStream In=socket.getinputstream (); 9         byte[] bytes=new byte[1024];10         int len=in.read (bytes);         System.out.println (New String (Bytes,0,len));         //server to client reply to         OutputStream out=socket.getoutputstream ();         out.write ("Received! over! ". GetBytes ());         server.close ();     
1//Client 2 public class TCPCLient {3 public     static void Main (string[] args) throws IOException {4         //1. Create a Socket object, Connect Server 5         socket socket=new socket ("127.0.0.1", 7777); 6         //2. Method of getting byte output stream in socket object via client socket Object 7         OutputStream Out=socket.getoutputstream (); 8         //3. Write data to Server 9         out.write ("Hello Server". GetBytes ());         //Receive server-side reply one by one         InputStream in= Socket.getinputstream ();         byte[] bytes=new byte[1024];13         int len=in.read (bytes);         System.out.println (New String (bytes, 0, Len)),         and/or release resources         socket.close ();     

File Upload case

Code Demo:

1 public class TCPServer {2 public     static void Main (string[] args) throws IOException {3         serversocket server=new ServerSocket (5555); 4         Socket socket=server.accept (); 5         //Clear Data source 6         InputStream in=socket.getinputstream (); 7         //Clear Destination 8         file File=new file ("X:\\upload"), 9         if (!file.exists ()) {ten             file.mkdirs ();         }12         //domain + millisecond value 13         String filename= "Oracle" +system.currenttimemillis () + ". jpg";         FileOutputStream fos=new FileOutputStream (file+file.separator+filename);         //copy +         int len=0;17         Byte[] Bytes=new  byte[1024];18         while ((Len=in.read (bytes))!=-1) {             fos.write (bytes,0,len); 20         }21         //reply to client         outputstream out=socket.getoutputstream ();         out.write ("Upload successful! ". GetBytes ());         //Release Resources         Server.close ();         fos.close ();     }29}
1 public class Tcpclinet {2 public     static void Main (string[] args) throws IOException {3         Socket socket=new Socke T ("192.168.1.171", 7000); 4         OutputStream Out=socket.getoutputstream (); 5         //Explicit data source 6         FileInputStream fis=new fileinputstream ("x:\\ Test\\img1.jpg "); 7         int len=0; 8         byte[] Bytes=new byte[1024]; 9         //File copy ten while         ((Len=fis.read (bytes))!=-1) {             One Out.write (Bytes,0,len);         }13         //Tell the server not to read the end of the         socket.shutdownoutput ();/         server-side reply 16         InputStream In=socket.getinputstream ();         len=in.read (bytes);         System.out.println (New String ( Bytes, 0, len);         //Release Resources         Fis.close ();         socket.close ();     }23 24}
File upload case multi-threaded version

Code Demo:

1 public class Demo {2 public     static void Main (string[] args) throws IOException {3         serversocket server=new Server Socket (6000); 4 while         (true) {5             socket socket=server.accept (); 6             new Thread (new Upload (socket)). Start (); 7         }    8     }9}
 1 public class Upload implements runnable{2 private socket socket, 3 public Upload (socket socket) {4 thi S.socket=socket; 5} 6 public void Run () {7///Explicit data source 8 FileOutputStream Fos=null; 9 try {ten INP             Utstream in= Socket.getinputstream (); 11//Clear Destination: File File=new file ("X:\\upload"); 13 if (!file.exists ()) {file.mkdirs (); 15}16//domain + millisecond value-String filename=             "Oracle" +system.currenttimemillis () + ". jpg"; fos=new fileoutputstream (file+file.separator+filename); 19 copy int len=0;21 byte[] bytes=new byte[1024];22 while ((Len=in.read (bytes))! = -1) {fos.write (Bytes,0,len); 24}25//reply client OutputStream Out=socket . Getoutputstream (); Out.write ("Upload successful! ". GetBytes ()); the catch (IOException e) {e.printstacktrAce ();}finally{31//Release resource: try {fos.close (); IOException e) {e.printstacktrace (); 36}37}38}39}

JAVA--UDP Communication and TCP communication

Related Article

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.