Java socket packet communication (I) socket establishment, socket Packet

Source: Internet
Author: User

Java socket packet communication (I) socket establishment, socket Packet

Java socket packet communication (I) socket Establishment

Today, I will share with you how to use socket for communication in java. Let's take a look at TCP/IP and udp:

TCPYesTransfer Control ProtocolIs a connection-oriented protocol for reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.

UDPYesUser datasync ProtocolThe abbreviation is a connectionless protocol. Each datagram is an independent information, including the complete source address or destination address. It is transmitted to the destination in any possible path on the network, therefore, whether or not to reach the destination, the time to arrive at the destination, and the correctness of the content cannot be guaranteed.

(1)Comparison between the two

UDP:

TCP:

(2) Applications

Note: The above content is found online. To save time, I will not write it myself.

 

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

Socket communication is divided into client and server. The server listens continuously. When the server listens to a client sending a communication request to it, both parties establish a connection. After the communication is completed, both parties close the connection.

First, let's look at how to build the client:

Public class SocketClient {public static void main (String [] args) throws IOException {try {Socket socket = new Socket ("127.0.0.1", 5200); System. out. println ("client start... "); // send a customer request to the local port 52000 BufferedReader br = new BufferedReader (new InputStreamReader (System. in); // The BufferedReader object PrintWriter write = new PrintWriter (socket. getOutputStream (); // obtain the output stream from the Socket object and construct the PrintWriter object Buffered Reader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // obtain the input stream from the Socket object and construct the corresponding BufferedReader object String readline; readline = br. readLine (); // read a string from the system standard input while (! Readline. equals ("end") {// If the string read from the standard input is "end", stop the loop write. println (readline); // outputs the string read from the system standard input to the Server write. flush (); // refresh the output stream so that the Server immediately receives the string System. out. println ("Client:" + readline); // print the read string System on the System standard output. out. println ("Server:" + in. readLine (); // read a string from the Server and print it to the standard output. readline = br. readLine (); // read a string from the system standard input} // continue loop write. close (); // close the Socket output stream in. close (); // close Socket input stream socket. close (); // close Socket} catch (Exception e) {System. out. println ("can not listen to:" + e); // error, print error message }}}

 

The following figure shows how to build a server:

Public class SocketService {public static void main (String [] args) throws IOException {SocketService socketService = new SocketService (); socketService. oneServer ();} public void oneServer () {try {ServerSocket server = null; try {server = new ServerSocket (5200); System. out. println ("server start is OK... "); // create a ServerSocket in Port 5200 to listen to customer requests} catch (Exception e) {System. out. println ("can not listen to:" + e); // Error, print error message} Socket socket = null; try {Socket = server. accept (); // use accept () to block and wait for customer requests. When a customer // request arrives, a Socket object is generated and the catch (Exception e) {System. out. println ("Error. "+ e); // error, print error message} String line; BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // obtain the input stream from the Socket object and construct the corresponding BufferedReader object PrintWriter writer = new PrintWriter (socket. getOutputStream (); // output from the Socket object And construct the PrintWriter object BufferedReader br = new BufferedReader (new InputStreamReader (System. in); // The BufferedReader object System is constructed by the System standard input device. out. println ("Client:" + in. readLine (); // print the string line that is read from the client on the standard output = br. readLine (); // read a string from the standard input while (! Line. equals ("end") {// If the string is "bye", the cyclic writer is stopped. println (line); // output the writer string to the client. flush (); // refresh the output stream so that the Client immediately receives the string System. out. println ("Server:" + line); // print the read string System on the System standard output. out. println ("Client:" + in. readLine (); // read a string from the Client and print it to the standard output line = br. readLine (); // read a string from the system standard input} // continue loop writer. close (); // close the Socket output stream in. close (); // close Socket input stream socket. close (); // close Socket server. close (); // close ServerSocket} catch (Exception e) {// error, print error information System. out. println ("Error. "+ e );}}}

This is where we first start the server and then start the client (the sequence cannot be messy). When I input abc on the client, the following is true:

Open the console on the server and you will see the message sent by the client:

Then we enter 123:

Open the console of the client:

The message returned by the server is displayed, proving that our communication is okay.

The preceding server can only listen to one client. To listen to multiple clients, modify the server:

public  void manyServer() throws IOException{     boolean flag = true;      ServerSocket serverSocket = null;      serverSocket = new ServerSocket(5200);      int clientNum = 0;      while(flag){          new SocketServerTherd(serverSocket.accept(), clientNum).start();          clientNum++;      }      serverSocket.close();    }
Public class SocketServerTherd extends Thread {Socket socket = null; int clientNum = 0; public SocketServerTherd (Socket socket, int num) {this. socket = socket; this. clientNum = num + 1;} public void run () {try {String line; BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // obtain the input stream from the Socket object and construct the corresponding BufferedReader object PrintWriter writer = new PrintWriter (socket. getOutputSt Ream (); // obtain the output stream from the Socket object and construct the PrintWriter object BufferedReader br = new BufferedReader (new InputStreamReader (System. in); // The BufferedReader object System is constructed by the System standard input device. out. println ("Client:" + in. readLine (); // print the string line that is read from the client on the standard output = br. readLine (); // read a string from the standard input while (! Line. equals ("end") {// If the string is "bye", the cyclic writer is stopped. println (line); // output the writer string to the client. flush (); // refresh the output stream so that the Client immediately receives the string System. out. println ("Server:" + line); // print the read string System on the System standard output. out. println ("Client:" + in. readLine (); // read a string from the Client and print it to the standard output line = br. readLine (); // read a string from the system standard input} // continue loop writer. close (); // close the Socket output stream in. close (); // close Socket input stream socket. close (); // close Socket} catch (Exception e) {// error, print error information System. out. println ("Error. "+ e );}}}

Let's talk about it today. Tomorrow I will tell you how to use packets for traffic. If you have any questions, let's discuss them together! Pai_^

 

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.