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 classclientdemo{ Public Static voidMain (string[] args)throwsunknownhostexception, IOException {Socket s=NewSocket ("127.0.0.1", 10004); BufferedReader buf=NewBufferedReader (NewFileReader ("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=NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream ()));  while((Line=buf.readline ())! =NULL) {out.write (line);            Out.newline ();        Out.flush ();        } s.shutdownoutput (); BufferedReader in=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); String Str=In.readline ();                System.out.println (str);                S.close ();    Buf.close (); }}

Server-side:

 Public classserverdemo{ Public Static voidMain (string[] args)throwsIOException {serversocket ss=NewServerSocket (10004); Socket s=ss.accept (); BufferedReader in=NewBufferedReader (NewInputStreamReader (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=NewBufferedWriter (NewFileWriter ("C:\\users\\administrator\\desktop\\2.txt"));  while((Line=in.readline ())! =NULL) {buf.write (line);            Buf.newline ();        Buf.flush (); } PrintWriter out=NewPrintWriter (S.getoutputstream (),true); Out.println ("Transmission is successful!" ");        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{    publicstaticvoidthrows  IOException     {        serversocket Server=new serversocket (11000);        Socket client=server.accept ();        PrintWriterout =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 classsocketserver{ Public Static voidMain (string[] args)throwsIOException {serversocket server=NewServerSocket (11000); Socket Client=server.accept (); PrintWriter out=NewPrintWriter (Client.getoutputstream (),true); BufferedReader in=NewBufferedReader (NewInputStreamReader (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 classclientdemo{ Public Static voidMain (string[] args)throwsunknownhostexception, IOException {Socket s=NewSocket ("192.168.1.120", 8080); PrintWriter out=NewPrintWriter (S.getoutputstream (),true); //will request hair to the serverOut.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 smallout.println (); BufferedReader in=NewBufferedReader (NewInputStreamReader (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 run the above client code, and you can see the response data returned by Tomacat:

  

  

  

TCP Communication for Java network programming

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.