Java Socket Message Communication (i) socket creation

Source: Internet
Author: User

Java Socket Message Communication (i) socket creation

Come and share with you today how to use the socket for communication in Java. Let's take a look at TCP/IP and UDP for a second:

TCP is the short name of Transfer Control Protocol and is a connection-oriented protocol that guarantees reliable transmission. With the TCP protocol transmission, a sequential error-free data stream is obtained. A connection must be established between the sender and the receiver's paired two sockets to communicate on the basis of the TCP protocol, and when a socket (usually a server socket) waits for a connection, the other socket can require a connection. Once the two sockets are connected, they can carry out two-way data transfer and both can send or receive operations.

UDP is the abbreviation of User Datagram Protocol , is a non-connected protocol, each datagram is a separate information, including the full source address or destination address, it on the network with any possible path to the destination, so can reach the destination, The time to reach the destination and the correctness of the content are not guaranteed.

(a) A comparison between the two

UDP :

    1. The full address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.
    2. When UDP transmits data with a size limit, each transmitted datagram must be limited to 64KB .
    3. UDP is an unreliable protocol in which datagrams sent by the sender do not necessarily reach the receiver in the same order.

TCP :

    1. Connection-oriented protocols, which are necessary to establish a connection before data is transferred between sockets, require connection time in TCP.
    2. TCP Transmission data size limit, once the connection is established, the socket on both sides can transfer large data in a uniform format.
    3. TCP is a reliable protocol that ensures that the receiver is getting all the data sent by the sender in full and proper order.
(ii) application
    1. TCP has a strong vitality in network communications, such as remote Connection (Telnet) and file Transfer (FTP), which require the data to be reliably transmitted over an indefinite length. But reliable transmission is to pay a price, the correctness of the data content of the test must occupy the computer processing time and network bandwidth , so the efficiency of TCP transmission is inferior to UDP High .
    2. UDP is simple to operate and requires less monitoring, so it is often used for client/server applications in decentralized systems with high LAN reliability. For example, the video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, it is obvious that using UDP is more reasonable.

Note: The above content is found on the Internet, in order to save time, I will no longer write their own.

Let's look at how to build the socket environment:

Socket communication is divided into client and server side. The server will not stop listening, when the server side to hear the client to send them a communication request, the two sides establish a connection. After the communication is complete, the two sides close the connection.

Let's start by looking at how to build a client:

1  Public classsocketclient {2      Public Static voidMain (string[] args)throwsioexception{3     Try{4Socket socket=NewSocket ("127.0.0.1", 5200);5SYSTEM.OUT.PRINTLN ("Client start ...");6             //make a customer request to port 52000 on this machine7BufferedReader br=NewBufferedReader (NewInputStreamReader (system.in));8             //constructing BufferedReader objects from System standard input devices9PrintWriter write=NewPrintWriter (Socket.getoutputstream ());Ten             //The output stream is obtained by the socket object, and the PrintWriter object is constructed OneBufferedReader in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); A             //The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed - String ReadLine; -Readline=br.readline ();//reads a string from the system standard input the              while(!readline.equals ("End")){ -   //stop Looping if the string read in from standard input is "end" - write.println (readline); -   //output A string read from the system standard input to the server + Write.flush (); -   //refreshes the output stream so that the server receives the string immediately +System.out.println ("Client:" +readline); A   //Print the Read-in string on the system standard output atSystem.out.println ("Server:" +in.readline ()); -   //reads a string from the server and prints it to the standard output -Readline=br.readline ();//reads a string from the system standard input -}//Continue looping -Write.close ();//close the socket output stream -In.close ();//close the socket input stream inSocket.close ();//Close Socket -}Catch(Exception e) { toSystem.out.println ("Can not listen to:" +e);//error, printing error message +         } -     } the}

Here is the server-side build:

1  Public classSocketservice {2    Public Static voidMain (string[] args)throwsioexception{3Socketservice Socketservice =NewSocketservice ();4 socketservice.oneserver ();5   }6    Public  voidOneserver () {7     Try{8ServerSocket server=NULL;9       Try{TenServer=NewServerSocket (5200); OneSYSTEM.OUT.PRINTLN ("Server Start is OK ..."); A         //Create a ServerSocket to listen for customer requests on port 5200 -}Catch(Exception e) { -System.out.println ("Can not listen to:" +e); the           //error, printing error message -       } -Socket socket=NULL; -       Try{ +socket=server.accept (); -         //use the Accept () block to wait for a customer request, a customer +         //When the request arrives, a socket object is generated and the execution continues A}Catch(Exception e) { atSystem.out.println ("Error.") +e); -         //error, printing error message -       } - String Line; -BufferedReader in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); -       //The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed inPrintWriter writer=NewPrintWriter (Socket.getoutputstream ()); -       //The output stream is obtained by the socket object, and the PrintWriter object is constructed toBufferedReader br=NewBufferedReader (NewInputStreamReader (system.in)); +       //constructing BufferedReader objects from System standard input devices -System.out.println ("Client:" +in.readline ()); the       //print a string read from the client on standard output *Line=br.readline (); $       //reads a string from a standard inputPanax Notoginseng        while(!line.equals ("End")){ -       //If the string is "Bye", the loop is stopped the writer.println (line); +         //output The string to the client A Writer.flush (); the         //refreshes the output stream so that the client receives the string immediately +System.out.println ("Server:" +Line ); -         //Print the Read-in string on the system standard output $System.out.println ("Client:" +in.readline ()); $         //reads a string from the client and prints it to the standard output -Line=br.readline (); -         //reads a string from the system standard input the}//Continue looping -Writer.close ();//close the socket output streamWuyiIn.close ();//close the socket input stream theSocket.close ();//Close Socket -Server.close ();//Close ServerSocket Wu}Catch(Exception e) {//error, printing error message -System.out.println ("Error.") +e); About     } $   } -}

This is the first time we start the server side, and then start the client (not in order), when I enter ABC on the client, as follows:

We then open the server console, we will see the message sent by the client:

Then we'll enter 123:

Let's open the client console again:

This shows the information of the service-side callbacks, proving that our communication is no problem.

Java Socket Message Communication (i) socket creation

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.