TCP Communication for Java network programming

Source: Internet
Author: User

I. Overview

The socket class is the underlying class in which Java performs client-side TCP operations, and the class itself uses code to communicate through the local TCP stack of the host operating system. The socket class method establishes and destroys the connection, setting various socket options.

The ServerSocket class is the base class for Java server-side operations, which run on the server, listen for inbound TCP connections, and each socket server listens to a port on the server, and when the client of the remote host attempts to connect to the port, the server is awakened. and returns a normal socket object that represents the socket between the two hosts.

Second, what is TCP?

TCP is a connection-oriented, reliable, byte-stream-based Transport layer communication protocol. The TCP communication is divided into the client and the server side, the corresponding object is socket and ServerSocket respectively.

When a computer needs to connect to another remote computer, the TCP protocol lets them establish a connection: the virtual link that is used to send and receive data. The TCP protocol collects the packets and puts them in the proper order and sends them back to the receiving side before restoring them correctly. In order to ensure that the packet is accurate in the transmission, TCP uses a recurrence mechanism: When a communication entity sends a message to another communication entity, it needs to receive confirmation from another entity, and if no acknowledgement is received, the information just sent is re-posted.

  

Third, TCP communication 1, constructor

The socket class implements a client socket, through which the constructor can specify the host and port that you want to connect to. The host can be specified as InetAddress or string, and the port is always specified as an int value between 0 and 65535.

Socket s=new socket ("127.0.0.1", 10001);//create a stream socket and connect it to the specified port number on the specified host

The ServerSocket class implements a server socket. A server socket waits for a request to pass through the network, performs some action based on the request, and then returns the result to the requestor.

ServerSocket ss=new ServerSocket (10001);//create a server socket bound to a specific port

2. Example: TCP File Replication

Client:

public class clientdemo{public static void Main (string[] args) throws Unknownhostexception, IOException {so                Cket s=new Socket ("127.0.0.1", 10004);        BufferedReader buf = new BufferedReader (New FileReader ("C:\\users\\administrator\\desktop\\1.txt"));                String Line=null;                /*printwriter out=new PrintWriter (S.getoutputstream (), true);        while ((Line=buf.readline ())!=null) {out.println (line);        } */BufferedWriter out=new BufferedWriter (New OutputStreamWriter (S.getoutputstream ()));            while ((Line=buf.readline ())!=null) {out.write (line);            Out.newline ();        Out.flush ();        } s.shutdownoutput ();                BufferedReader in=new BufferedReader (New InputStreamReader (S.getinputstream ()));                String Str=in.readline ();                System.out.println (str);                S.close ();    Buf.close (); }}

Server-side:

public class serverdemo{public    static void Main (string[] args) throws IOException    {        ServerSocket ss=new ServerSocket (10004);            Socket s=ss.accept ();            BufferedReader in=new BufferedReader (New InputStreamReader (S.getinputstream ()));        String Line=null;                /*printwriter buf=new PrintWriter (New FileWriter ("C:\\users\\administrator\\desktop\\2.txt"), true);        while ((Line=in.readline ())!=null)        {                buf.println (line);        } *        /BufferedWriter buf=new bufferedwriter (New FileWriter ("C:\\users\\administrator\\desktop\\2.txt"));        while ((Line=in.readline ())!=null)        {                buf.write (line);            Buf.newline ();            Buf.flush ();        }        PrintWriter out=new PrintWriter (S.getoutputstream (), true);        OUT.PRINTLN ("Transfer succeeded! ");        Ss.close ();        Buf.close ();    }}

IV. application of socket in browsing

We can write the server side in Eclipse and then access it using the browser.

eg, server-side code is:

public class socketserver{public    static void Main (string[] args) throws IOException     {        ServerSocket server= New ServerSocket (11000);        Socket client=server.accept ();        PrintWriter out=new PrintWriter (Client.getoutputstream (), true);        OUT.PRINTLN ("Hello! ");        Server.close ();    }}

Then open IE browser, enter http://192.168.1.120:11000/(192.168.1.120 as the native IP address) in the address, the result is shown as:

  

In a normal application, the browser makes a request to the TOMACAT server to get the resources such as Web images. And TOMCA is the server-side software written in Java.

Now we write the server side as:

public class socketserver{public    static void Main (string[] args) throws IOException     {        ServerSocket server= New ServerSocket (11000);        Socket client=server.accept ();        PrintWriter out=new PrintWriter (Client.getoutputstream (), true);        BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));        String Line=null;        while ((Line=in.readline ())!=null)            System.out.println (line);        OUT.PRINTLN ("Hello! ");        Server.close ();    }}

Then, using browser access, you can see that the browser (client) sends the server-side request header data:

  

Using the above principles, we can write our own browser-side (client) software similar to IE. First add a demo.html resource to the Tomcat installation directory C:\apache-tomcat-7.0.62\webapps\myweb, and then write the client with the following code:

public class clientdemo{public    static void Main (string[] args) throws Unknownhostexception, IOException    {        Socket s=new socket ("192.168.1.120", 8080);        PrintWriter out=new PrintWriter (S.getoutputstream (), true);                The hair will be requested to the server        out.println ("get/myweb/demo.html http/1.1");        Out.println ("accept:*/*");        Out.println ("host:192.168.1.120:11000");        Out.println ("connection:keep-alive");                Output blank line, this step is not less        out.println ();        BufferedReader in=new BufferedReader (New InputStreamReader (S.getinputstream ()));        String Line=null;        Returns the server's response file        while ((Line=in.readline ())!=null)        {            System.out.println (line);        }        S.close ();    }}

Next, start Tomcat. That is, double-click the Startup.bat file in C:\apache-tomcat-7.0.62\bin. Then run the above client code, and you can see the response data returned by Tomacat:

  

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP Communication for Java network programming

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.