Java TCP Communication

Source: Internet
Author: User

1.Socket principle

1) Socket Introduction

Sockets are often referred to as "sockets", which describe the IP address and port number, and are a handle to a communication chain. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and binds to a port, and the different ports correspond to different services. Applications typically make requests to the network through sockets or answer network requests. The socket and ServerSocket class libraries are located in the java.net package. ServerSocket for the server, socket is used when the resume network connection. When the connection succeeds, a socket instance is generated at both ends of the application, manipulating the instance to complete the required session.

2) Get local address and port number

    • Get the port number that is used locally
      int Getlocalport () return type int

        

    • Gets the local address of the socket binding
      InetAddress getlocaladdress ()

        

    • To get the local address method using InetAddress
      String Getcanonicahostname () returns a type of string

        

    • Get the fully qualified domain name for this IP address
      String gethostaddress () returns a type of string

        

3) Get the remote address and port number

    • Socket get Remote Port number method
      int Getport () return type int

        

    • Gets the remote address of the remote socket binding
      Inetaddress.getinetaddress ()

        

Case 1:socket Obtaining IP, port information

1. Set up the server side to use this machine as a demo

Import Java.io.ioexception;import Java.net.serversocket;import Java.net.socket;public class ServerSocketDemo {public static void Main (string[] args) {serversocket server;try {server = new ServerSocket (8080);  Create a serversocket and request a 8080 service port socket socket = server.accept ();  Blocking method, listening on the service port, waiting for the client link and returning a socket instance} catch (IOException e) {e.printstacktrace ();}}}

2. Set up the client to use this machine as a client demo

After the client is set up, start the server and then start the client to connect to the server, and then you can see the IP and port information of the output port and the remote terminal after the connection is successful.

Import Java.io.ioexception;import Java.net.inetaddress;import Java.net.socket;public class SocketInetAddressDemo { public static void Main (string[] args) {try {socket socket = new socket ("localhost", 8080);//Gets the port number used locally int port = socket.ge Tlocalport (); SYSTEM.OUT.PRINTLN ("Local use port number:" +port); inetaddress add = Socket.getlocaladdress ();  Get local address information//use inetaddress to get local address string hostname = Add.getcanonicalhostname (); SYSTEM.OUT.PRINTLN ("Local address:" +hostname);//Gets the fully qualified domain name of this IP string hostadd = add.gethostaddress (); SYSTEM.OUT.PRINTLN ("Qualified Domain name:" +hostadd);//Gets the port number of the far end int desport = Socket.getport (); SYSTEM.OUT.PRINTLN ("Remote port number:" +desport);//Get remote ipinetaddress Inetadd = socket.getinetaddress (); System.out.println (Inetadd);} catch (IOException e) {e.printstacktrace ();}}} /* Run Result: Local use port number: 62565 Local address: 127.0.0.1 Limited domain name: 127.0.0.1 Remote port number: 8080localhost/127.0.0.1*/

4) Get the network input stream and the network output stream

Using the socket to get the input and output streams, these two methods use the key method of socket communication, the socket that encapsulates the TCP protocol is based on the flow of communication, so after we create the two connections, we only need to obtain the corresponding input stream and output stream to achieve communication.

    • Returns the input stream for this socket
      InputStream getInputStream ()

       

    • Returns the output stream for this socket
      Outputstream.getoutputstream ()

        

Specific code examples:

public void Testsocket () throws exception{    socket socket = new socket ("localhost", 8080);    InputStream in = Socket.getinputstream ();    OutputStream out = Socket.getoutputstream ();}

  

5) Close Method

When the socket is used for communication, close the socket to release system resources.

void Close ()

  

2.Socket Communication Model

1) server-side ServerSocket monitoring

Java.net.ServerSocket is run in a server-side application, typically creating a serversocket requires specifying the service port number, and then listening to the Sokcet connection, which is monitored by:

Socket Accept ()

This method is a blocking method, until a client is connected through a socket, the accept encapsulates a socket that encapsulates information about that client and communicates with the client through the socket.

Create ServerSocket and request Service port 8080ServerSocket Server = new ServerSocket (8080); the//accept () method will cause blocking Socketsocket socket = server.accept () until a socket is connected and returns the requested connection;

  

2) client-side socket connection

When the server-side ServerSocket calls the Accept method to block waiting for a client connection, we can initiate a connection to the server by creating a socket in the client application.

It is important to note that the connection is initiated at the same time that the socket is created, and if the connection exception throws an exception, we usually create the socket with the address and port number of the server.

Parameter 1: Server IP address  parameter 2: Service port port number SOCKET socket = new socket ("localhost", 8080);

  

3) C/s terminal communication model

c/s i.e.: client-server, client to server

The client-server communication model is as follows:

    1. Service-side Creation ServerSocket
    2. Listening for client connections by calling ServerSocket's Accept method
    3. The client creates a socket and specifies the address and port of the server to establish a connection to the server
    4. When a client connection is found by the server accept, the socket for the client should be acquired
    5. The two sides obtain the corresponding input and output stream for data communication through the socket respectively.
    6. Close connection after communication ends

  

Java TCP Communication

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.