Java Network programming TCP programs, server and client interaction processes, and basic operating procedures.

Source: Internet
Author: User

1. What is Network programming

  Network programming is actually the realization of two computer data exchange (interaction).

You can communicate with other computers through a network protocol, either directly or indirectly. (HTTP protocol, TCP/IP protocol, etc.)

2.implementation process of TCP network programming

It is mainly divided into server-side (servers) and clients (client).

Through this diagram we can actually understand how the server and client interaction process is.

The most important thing in implementing these principles is that the Socket class is also called a socket. applications typically make requests to the network through sockets or answer network requests.

Server-side

1. First create the ServerSocket object and set the port number to communicate with the outside world, so that it can be accessed by other computers (where the port number can be obtained casually but is between 1024~65535, because 0~ 1023 used by pre-communicated services (such as HTTP for 80 ports, Telnet to 23 ports, etc.).

ServerSocket servesocket = new ServerSocket (2222);

  

2. Then call the Accept () method, listen for the connection request, accept the link if the client requests a connection, and return the communication socket (socket).

Socket socket = serversocket.accept ()

3. Get the input and output stream

Get the input stream of the socket

BufferedReader br = new BufferedReader (New Getinputsteamreader (Socket.getinputstream ()))

Get the output stream of the socket

PrintWriter out = new Perintwriter (Socket.getoutputstream ())

  

4. The end is to close the Scoket

Socket.close ()

Client

1. Create the socket object, and implement the socket's parameter construction method, enter the IP address and port number (here address is the IP, port is the port number)

Socket socket = new Socket (inetaddress address,int port)

2. Get the input and output stream of the socket

Get the input stream of the socket

BufferedReader br = new BufferedReader (New Getinputsteamreader (Socket.getinputstream ()))

Get the output stream of the socket

PrintWriter out = new Perintwriter (Socket.getoutputstream ())

3. Close the socket

Socket.close ()

The above is the main process of implementing server-side and client interaction. Let's take a look at the specific examples:

Server-side

1      Public Static voidServer () {2         Try {3             //Create a ServerSocket object and define a connection port4ServerSocket ServerSocket =NewServerSocket (2222); 5             //Enable connection monitoring6Socket socket =serversocket.accept (); 7             //get socket output stream8BufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); 9             //get socket input streamTenPrintWriter out =NewPrintWriter (Socket.getoutputstream ());  One             //get information from the client through the output stream AString str=br.readline (); -             //Output Information - System.out.println (str); the              -             //send a message through the input flow to the client -Out.write ("Successfully received client-delivered information"); -             //Flush Write + Out.flush (); -              +             //turn off the output stream A br.close (); at             //close the input stream - out.close (); -             //Close ServerSocket - serversocket.close (); -}Catch(IOException e) { -             //TODO auto-generated Catch block in e.printstacktrace (); -         } to     } +  -      Public Static voidMain (string[] args) { the Server (); *}

Client

1  Public Static voidClien () {2         Try {3             //create the socket object and write the IP address and port number (this can be written by hand, I write here is the simplest example of interaction once)4Socket socket =NewSocket ("192.168.0.102", 2222);5             //Get input stream6PrintWriter out =NewPrintWriter (Socket.getoutputstream ());7BufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ()));8             //read information entered from the console9BufferedReader in =NewBufferedReader (NewInputStreamReader (system.in));Ten             //get information from console input OneString str=in.readline (); A             //writes information from the console to - out.write (str); -             //Flush Write the Out.flush (); -             ///Turn off the input stream (shutdown is the only one that closes the input stream, if it is not closed, it will be written indefinitely, the client and the service end are stuck, and the next action cannot be performed) -             //If the Out.close () is used, the stream of the socket will be closed and the socket closed error will be displayed when the client information needs to be read below.  - socket.shutdownoutput (); +              -             //get information from the server side +String serverstr=br.readline (); A System.out.println (SERVERSTR); at             //Close - br.close (); - Socket.close ();  -}Catch(unknownhostexception e) { -             //TODO auto-generated Catch block - e.printstacktrace (); in}Catch(IOException e) { -             //TODO auto-generated Catch block to e.printstacktrace (); +         } -     } the  *      Public Static voidMain (string[] args) { $ Clien ();Panax Notoginseng}

What I'm writing here is just the simplest operation of a single interaction between the server and the client.

If you want to implement the interaction until you enter a word specifier exit the interaction, you can use loops.

  1  while  ( true  ) {  2  String str = Br.readline ();   3   System.out.println (str);   4   5  Out.write ("Successfully received client-delivered information"   6   Out.flush ();   7  if  (Str.equals ("End"   8  break   9  }  10 } 

The above is the code for the server-side loop interaction. Client's pretty much, I don't write.

A Final summary : The process of implementing the interaction

1. Create a Socket object (server-side Create ServerSocket object, and listen)

2. Get the input and output stream

3. Close

In fact, this is mainly the three points, if you want to make more complex interaction, you can continue to add in the input and output

Java Network programming TCP programs, server and client interaction processes, and basic operating procedures.

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.