Socket interface calls in Java

Source: Internet
Author: User

The most recent project in the interface communication this piece is mainly called the UnionPay system socket interface, we are the client, that is, send a request to receive the return message of the party. Before pasting the code, you should still know the basics of the socket.

Socket the basic concept

1 . Establish a connection

When a network connection needs to be established, a machine must be running a program, waiting for the connection at any time, while the other end of the program sends a connection request to it. This is similar to a telephone system where one party must make a call and the other must wait for the phone to connect.

The process for establishing a connection is:

(1) First generate a ServerSocket instance object on the server side, listen to the client's connection request at any time.

(2) When the client needs to connect to the server, a socket instance object is generated accordingly, and a connection request is made, where the host parameter indicates the hostname, and the port parameter indicates the host port number.

(3) After the server receives the client's request through the Accept () method, it opens up an interface to connect with it and generates the required I/O data stream.

(4) The client and server communication are through a pair of InputStream and OutputStream, after the end of the communication, the two ends of the corresponding socket closed respectively.

2. Connection Address

When you make a call, the caller must know the number you want to dial in advance, and when the program establishes the network connection, you also need to know the address or host name.

Additionally, the network connection requires a port number (which can be used as the extension number for the phone), and after connecting to the correct host, a specific password needs to be confirmed for that connection.

3. Port number

In a TCP/IP system, the port number is made up of 16-bit binary integers, which is between 0-65535. In practice, the first 1024 port numbers are pre-defined as specific services and are generally not available unless you want to connect to them (such as TELNET,SMTP,MAIL,FTP, etc.). Before two programs are connected, you must agree with each other that the client is responsible for initializing the connection and the server is waiting for the request at any time. The connection is established only if the client and server side specify a port number consistent. This connection cannot be established if the port number used by the two programs in the system is inconsistent.

4. Network connection mode

In Java, the connection to the TCP/IP interface is implemented by the classes in the java.net package. Represents how the client and server side work during the socket connection.

Each server side has a port number, which may correspond to multiple port numbers if multiple services are running on a single machine. At the end of the communication, the respective sockets are closed, without affecting the other ports.

Socket Basic steps of communication

The basic structure of the program for network communication using the socket is similar, no matter how complete the function of a socket communication program and how complex the program is, its basic structure is the same. The process of client-to-server communication consists of the following four basic steps:

(1) Specify a port number on the server side to wait for the connection, specifying a host and port number on the client side to create the Socket/serversocket instance on the client and server sides.

(2) Open the input and output stream connected to the socket.

(3) using the input and output stream, according to a certain protocol to read and write to the socket.

(4) Turn off the input and output stream and socket

Usually, the main work of the programmer to the completion of the function of the hit Device Step (3) programming, the first (1), (2), (4) Steps for all communication procedures are almost the same.

Socket constructors that are commonly used in classes

1:socket (inetaddress address,int Port): This method is used to create a link that sends a connection request to a server-side program on the specified port on the specified IP address

2:socket (inetaddress address,int port): Ibid., but this method allows connection requests to be sent to the server via a hostname string

Socket common methods in a class

1:inetaddress getlocaladdress (): Returns the local IP address with which the socket is connected

2:int getlocalport (): Returns the local port number to which the socket is connected

3:inetaddress getinetaddress (): Returns the IP address of the server to which the socket was established

4:int Getport (): Return and socket establish the port number of the connected server

5:inputstream getInputStream (): Returns the input stream of the current socket (common)

6:outputstream Getoutstream (): Returns the output stream of the current socket (common)

7:void Close (): Closes the current socket connection

ServerSocket the constructors commonly used in

1:serversocket (int port): This is the construction method used to listen on a specified port on the current server's default IP address, that is, to create a ServerSocket object on the specified IP and port

ServerSocket the methods commonly used in

1:socket Accept (): Generates blocking, listens on the specified port until a client sends a connection request (common)

2:void Close (): Close current ServerSocket

3:inetaddress getinetaddress (): Returns the IP address of the native that ServerSocket listens to

4:int getlocalport (): Returns the port number specified on the native IP address of the ServerSocket listener

5:int getsotimeout ():: void setsotimeout (int timeout) setting no corresponding waiting period (timeout) during connection

6:string toString (): Returns the native IP address and its port number as a string ServerSocket listener

Socker Programming of Communication

Finally it's time to put the code on .....

1. server-side programs

 Public Static voidMain (string[] args) {//defining ServerSocket and Socket objectsServerSocket SS =NULL;        Socket SK; //defines the sending string, which is the information received by the clientString sendstring = "hello! I am the server ... "; //defining the OutputStream classOutputStream s1out; //defining the DataOutputStream classDataOutputStream dos; //Connect via port 1314        Try {            //Create a serversocket and put the incoming port numberSS =NewServerSocket (1314); } Catch(Exception e) {e.printstacktrace (); }        //Loop through the listener to monitor connection requests         while(true) {            Try {                //listening for port requests, waiting for connectionsSK =ss.accept (); //get the data flow object connected to the socketS1out =Sk.getoutputstream (); DOS=NewDataOutputStream (s1out); //Send StringDos.writeutf (sendstring); //Close the data stream (but not close the socket connection)Dos.close ();                S1out.close ();            Sk.close (); } Catch(Exception e) {e.printstacktrace (); }        }    }

2. Client Programs

/*** Send a message to the server using the socket connection, accept the response information note that if the method is to be overridden by a different IP port, the IP * port is used as the request condition, and now it is changed to pass in the intrinsic parameter *@paramtext *@throwsException*/     Public Staticstring Sendbysocket (string text, string IP, int port)throwsException {Log.info ("Start a socket connection"); Socket Socket=NewSocket (IP, port); InputStream is=Socket.getinputstream (); InputStreamReader ISR=NewInputStreamReader (IS, "GBK"); //2. Get the client output streamOutputStream dos =Socket.getoutputstream (); Log.info ("Connecting to the server"); //3. Send a message to the serverDos.write (Text.getbytes ());        Dos.flush (); Log.info ("Successfully sent a message to the server"); //4. Get the input stream and read the server-side response informationBufferedReader br =NewBufferedReader (ISR); String Returninfo=Br.readline (); Log.info ("Server-side return data is:" +returninfo); //4. Close ResourcesBr.close ();        Isr.close ();        Is.close ();        Dos.close ();        Socket.close (); returnReturninfo; }

Socket interface calls in Java

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.