TCP Communication for Java network programming

Source: Internet
Author: User
Tags file copy

I. Overview

The socket class is the underlying class in which Java runs the clienttcp operation, which 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 underlying class for Java execution server-side operations, which perform server-based listening for inbound TCP connections. Each socketserver listens to a port on the server. When the client of the remote host attempts to connect to this port. 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.

TCP traffic is divided into the client and server side, the corresponding objects are sockets and ServerSocket respectively.

When a computer needs to connect to a remote computer, the TCP protocol lets them establish a connection: a virtual link for sending and receiving data.

The TCP protocol is responsible for collecting packets. And put them in the right order. The receive side is received before it is restored correctly.

To ensure that the packets are accurate in the transmission, TCP uses a resend mechanism: when a communication entity sends a message to a communication entity, it needs to receive a confirmation of the entity. If you do not receive a confirmation message, the information you just sent is re-posted.

  

Third, TCP communication 1, constructor

The socket class implements the 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,port to always specify 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 the server socket.

The server socket waits for the request to pass through the network. It runs certain operations based on the request. The result is then returned to the requestor.

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

2. Sample: TCP file copy

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 were able to write the server side in Eclipse. Then use the browser to access the interview.

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 and enter http://192.168.1.120:11000/(192.168.1.120 as the native IP address) in the address. The results are shown as:

  

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

Today 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 use the browser to access the questions. The ability to see the request header data sent to the server by the browser (client) is:

  

Use the above principle. We are able to write browser-side (client) software similar to IE. First add a demo.html resource to the Tomcat installation folder C:\apache-tomcat-7.0.62\webapps\myweb, and then write the client. The code is as follows:

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 response file for the server        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 execute the above client code, and you can see the response data returned by Tomacat:

  

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.