Java Network Programming Socket communication

Source: Internet
Author: User

TCP (transmission Control Protocol Transmission protocol ) is a connection-oriented, reliable, byte-stream-based Transport Layer communication protocol

UDP (user Datagram Protocol Subscriber Datagram Protocol) is a connectionless transport layer protocol in the OSI (open System interconnection Open Systems Interconnect) Reference Model, providing a simple, transaction-oriented, unreliable information delivery service

Basic differences between TCP and UDP

    • 1. Connection-based and no-connection
    • 2.TCP requires more system resources, less UDP;
    • 3.UDP program structure is relatively simple
    • 4. Stream mode (TCP) and datagram Mode (UDP);
    • 5.TCP guaranteed data correctness, UDP may drop packets
    • 6.TCP guaranteed Data order, UDP does not guarantee

One, TCP protocol communication

1. Server side:

    • A. Create a ServerSocket object while binding the listening port
    • B. Listen for client requests through the accept () method
    • C, after establishing the connection, read the request information sent by the client through the input stream
    • D. Send response information through output flow to client
    • E. Close the appropriate resources
 Packagecom.yyx.test;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTcpserversocket { Public Static voidMain (string[] args) {ServerSocket serversocket=NULL; Socket Socket=NULL; InputStream InputStream=NULL; OutputStream OutputStream=NULL; FileOutputStream FileOutputStream=NULL; Try {            //creates an ServerSocket object that indicates its own port number through the constructorServerSocket =NewServerSocket (9090); //The server listener calls its accept () method, returning the object of a socketSocket =serversocket.accept (); InputStream=Socket.getinputstream (); String Pathname= "F:" + file.separator + "Target.jpg"; File File=NewFile (pathname); FileOutputStream=Newfileoutputstream (file); /** Receive client send file and save to local file*/            byte[] B =New byte[1024]; intLen;  while(len = Inputstream.read (b))! =-1) {Fileoutputstream.write (b,0, Len); } String Strinfo= "You send the picture I have received success!" "; OutputStream=Socket.getoutputstream ();        Outputstream.write (Strinfo.getbytes ()); } Catch(Exception e) {e.printstacktrace (); } finally {            //close the corresponding stream and the socket, ServerSocket object            if(OutputStream! =NULL) {                Try{outputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(FileOutputStream! =NULL) {                Try{fileoutputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(InputStream! =NULL) {                Try{inputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                                    if(Socket! =NULL) {                Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(ServerSocket! =NULL) {                Try{serversocket.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }    }}

2, Client clients:

    • A. Create a socket object that indicates the address and port number of the server you want to connect to
    • b, after establishing the connection, send the request information through the output flow to the server side
    • C. Get the server's response information through the input stream
    • D. Close the appropriate resources
 Packagecom.yyx.test;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetAddress;ImportJava.net.Socket; Public classTcpclientsocket { Public Static voidMain (string[] args) {socket socket=NULL; OutputStream OutputStream=NULL; InputStream InputStream=NULL; FileInputStream FileInputStream=NULL; Try {            //Create a Socket object that indicates the IP address of the server and the port number of its receiver through the constructorSocket =NewSocket (Inetaddress.getbyname ("127.0.0.1"), 9090); String Pathname= "F:" + file.separator + "Source.jpg"; File File=NewFile (pathname); FileInputStream=Newfileinputstream (file); //Getoutputstream (): Send data, method returns OutputStream objectOutputStream =Socket.getoutputstream (); byte[] B =New byte[1024]; intLen;  while(len = Fileinputstream.read (b))! =-1) {Outputstream.write (b,0, Len); }                        //shutdownoutput (): Execute this method and explicitly tell the server to send it! Socket.shutdownoutput (); InputStream=Socket.getinputstream (); byte[] Banother =New byte[1024]; intLenanother;  while((Lenanother = Inputstream.read (banother))! =-1) {String str=NewString (banother, 0, Lenanother);            System.out.print (str); }        } Catch(Exception e) {e.printstacktrace (); } finally {            //close the corresponding stream and socket object, from backward to forward            if(InputStream! =NULL) {                Try{inputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(OutputStream! =NULL) {                Try{outputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(FileInputStream! =NULL) {                Try{fileinputstream.close (); } Catch(IOException e) {e.printstacktrace (); }            }                        if(Socket! =NULL) {                Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }    }}

Second, UDP protocol communication

Client

 Packagecom.yyx.test;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpclientsocket { Public Static voidMain (string[] args) {datagramsocket datagramsocket=NULL; Try{Datagramsocket=NewDatagramsocket (); String Str= "Hello, I am the data to be sent"; byte[] B =str.getbytes (); /** Create a datagram: Each datagram can not be greater than 64k, all record the data information, the IP, port number of the sending side, and the IP, port number of the receiving end to send to*/Datagrampacket Pack=NewDatagrampacket (b, 0, B.length, inetaddress.getbyname ("127.0.0.1"), 9090);        Datagramsocket.send (Pack); } Catch(Exception e) {e.printstacktrace (); } finally {            if(Datagramsocket! =NULL) {datagramsocket.close (); }        }    }}

Service Side

 Packagecom.yyx.test;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpserversocket { Public Static voidMain (string[] args) {datagramsocket datagramsocket=NULL; Try{Datagramsocket=NewDatagramsocket (9090); byte[] B =New byte[1024]; Datagrampacket Pack=NewDatagrampacket (b, 0, b.length);            Datagramsocket.receive (Pack); String Str=NewString (Pack.getdata (), 0, Pack.getlength ());        System.out.println (str); } Catch(Exception e) {e.printstacktrace (); } finally {            if(Datagramsocket! =NULL) {datagramsocket.close (); }        }    }}

Java Network Programming Socket communication

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.