Java Network Programming Fundamentals (ii)--TCP/IP-based socket programming

Source: Internet
Author: User
Tags fully qualified domain name

This section tells you something:

    • Client sockets: How to create and use Socket:socket, as well as socket options and exceptions.

    • Service-side sockets: How to create and use Serversocket:seversocket, and ServerSocket options

    • A simple client/server Dialogue program

    • Support for multi-client Client/server service Responder


Learn about network fundamentals and network protocols before you learn the network programming of your JDK.

TCP (Transmission Control Protocol) is a connection-based communication protocol. Reliable transmission

UDP (User Packet Protocol) communication protocol for unstable connections

The ports for TCP and UDP are as follows:

Telnet:23

SMTP (Simple Mail Transfer Protocol): 25

HTTP (Hypertext Transfer Protocol): 80

pop3:110


IP Address class inetaddress

Socket programming is intended to establish a network communication connection between the server-side IP and the client IP, so IP addressing is the basis for establishing a connection. The InetAddress class is the IP address wrapper class for Java, which represents the Internet Protocol address. IP address is a 32-bit or 128-bit unsigned number used by IP, it is a low-level protocol, and TCP and UDP protocols are built on it. The InetAddress class provides the following actions:

    1. The method that creates the InetAddress object.

The InetAddress class has no constructor, and to create an instance object of the class, you can obtain the object from a static method of the class.

(1) Get the Local address: Getlocalhost ()

function definition: public static inetaddress Getlocalhost () throws unkonwnhostexception; Example: try{//Get native address inetaddress local = Ineta    Ddress.getlocalhost (); SYSTEM.OUT.PRINTLN (local);} catch (Unkownhostexception e) {}

(2) Get address according to host name: Getbyname (String host);

(3) Get a set of addresses based on the hostname: Getallbyname (String host);

(4) Obtain address according to IP: getbyaddress (byte[] addr);

The IPV4 address, expressed in 4 bytes, uses 6 bytes in a IPv6

(5) based on hostname and IP address: getbyaddress (String host,byte[] addr)

2. Get the properties of the InetAddress class

Get the fully qualified domain name for this IP address

String Getcanonicalhostname ();

Returns the IP address string

String gethostaddress ();

Gets the host name of this IP address

String gethostname ();

3, determine the version of the address is IPv4 or IPv6

try{    //get the Local address     InetAddress local =  Inetaddress.getlocalhost ();     //ipv4  or ipv6    byte[ ] addr = local.getaddress ();     if (addr.length == 4) {   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("IP version  is ipv4");         int firstByte = addr[0];         if (firstbyte < 0) {             firstbyte += 256;        }         if ((firstbyte & 0x80)  == 0) {             system.out.println ("IP class  is a");         }else if ((Firstbyte&nbsP;&AMP;&NBSP;0XC0)  == 0) {             System.out.println ("IP class  is b");         }else if (( FIRSTBYTE&NBSP;&AMP;&NBSP;0XE0)  == 0) {             system.out.println ("IP class  is c");         }else  if ((firstbyte & 0xf0)  == 0) {             system.out.println ("IP class  is d");         }else if ((Firstbyte & 0xf8)  == 0) {             system.out.println ("IP class  is e");         }    }else if (addr.length == 6) {         system.out.prIngln ("ip  version  is ipv6");     }}catch (unkownhostexcetion e) {     e.printstacktrace ();}


4. Client Socket sockets

Sockets allow a program to treat a network connection as a stream, either to the Write section or to read bytes from the stream. Sockets block the bottom-level details of the network for programmers.

The socket is a section of two-way communication between two programs running on the network, it can accept the request, can also send the request, it is convenient to write the data transfer on the network.

The working procedure of the socket is as follows:

(1), connect to the remote machine

(2), bind to Port

(3), receive the connection from the remote machine to the bound port

(4), monitoring the arrival of data

(5), send data

(6), receive data

(7), close the connection


1. Creating a Socket Object

    • Set up a socket to host the port port, connect to the remote host, as follows:

The public socket (String host,int port) throws Unkownhostexception IOException, as an example: try{socket socket = new Socket ("www.ba Idu.om ", 80);} catch (Unkownhostexception Uex) {}catch (IOException e) {}
    • Creating a socket differs from the previous one in that it specifies the socket with the InetAddress object and throws IOException if there is an error

Public Socket (inetaddress host,int Port) throws IOException, examples are as follows: try{inetaddress addr = Inetaddress.getbyname ("Www.bai    Du.com "); Socket socket = new socket (addr,80);} Catch...


5. Server-side Socket ServerSocket

Each server socket runs on the server with a specific port that listens for TCP connections on this port. When the socket of the remote client attempts to connect to the specified port on the server, the server is activated, the client is determined to connect, and an inherent connection between the two hosts is turned on. Once the client has established a connection with the server, the data can be transferred between the two, and the data is passed through this intrinsic socket.

ServerSocket's work process is as follows:

(1), using the ServerSocket () method to create a new ServerSocket object on the specified port

(2), the ServerSocket object calls the Accept () method to listen for incoming connections on the specified port. Accept () is in a blocking state, knowing that a client is trying to establish a connection, and the Accept () method returns the socket object that connects the client to the server

(3), call the getInputStream () method or the Getoutputstream () method, or both, to establish an input or output stream that interacts with the client.

(4), the server and the client according to a certain protocol interaction, know to close the connection

(5), server, client, or both close the connection.

(6), the server back to the 2nd step, continue to listen to the next connection

1. Create a Seversocket object

Create a server socket bound to a specific port

ServerSocket (int port);

try{seversocket Server = new ServerSocket (12345);} catch (IOException e) {}

Creates a server socket with the specified backlog and binds it to the specified local port. The backlog represents the maximum queue length for incoming connections to indicate (requests to a connection) and denies the connection if the queue is full and is prompted by a connection. The backlog parameter must be a positive value greater than 0, and if the value passed is less than or equal to 0, the default is used.

ServerSocket (int port,int backlog);

try{seversocket Server = new ServerSocket (12345,20);} catch (IOException e) {}

The server-side example is as follows:

import java.io.bufferedreader;import java.io.ioexception;import java.io.inputstreamreader; import java.io.printwriter;import java.net.serversocket;import java.net.socket;/** *  @author  Administrator * Java socket  Server-side Simple example  */public class oneserver  {public static void main (String[] args)  {//  start server-side Serversocket server  = null;try {server = new serversocket (12345); SYSTEM.OUT.PRINTLN ("Server Startup" +server.getinetaddress (). Gethostaddress () + ":" +server.getlocalport ()); while (true) {// Listener client socket socket = server.accept (); SYSTEM.OUT.PRINTLN ("Client Connection" +socket.getinetaddress (). Gethostaddress () + ":" +socket.getport ());// Input and output stream Bufferedreader sin = new bufferedreader (New inputstreamreader (System.in)); Bufferedreader is = new bufferedreader (New inputstreamreader (Socket.getInputStream ()) ); Printwriter os&nBsp;= new printwriter (Socket.getoutputstream ());//Loop processing client input string line;while (line =  Is.readline ())  != null) {System.out.println ("received client:" +line), if (Line.equals ("Bye")) {System.out.println ( "Bye, I went to heaven"); else{//read keyboard input and reply to client os.println (Sin.readline ()); Os.flush ();}} Turn off input/output stream is.close (); Os.close ();//Close client Socket.close ();}}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  finally {try {server.close ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}

Client Example:

import java.io.bufferedreader;import java.io.ioexception;import java.io.inputstreamreader; import java.io.printwriter;import java.net.inetaddress;import java.net.socket;import  Java.net.unknownhostexception;public class oneclient {public static void main ( String[] args)  {// todo auto-generated method stubtry {//Connection Server socket  Socket = new socket (Inetaddress.getlocalhost (), 12345);//input/output stream bufferedreader sin =  new bufferedreader (New inputstreamreader (system.in)); Bufferedreader is = new bufferedreader (New inputstreamreader (Socket.getInputStream ()) ); Printwriter os = new printwriter (Socket.getoutputstream ());//loop-Read keyboard input string  Readline;while ((Readline = sin.readline ())  != null) {os.println (readLine); Os.flush ();// Read server-side reply String responeline = is.readline (); System.out.println ("Server-side reply:" +responeline);} Close the output stream is.close (); Os.close ();//Close client Socket.close ();}  catch  (unknownhostexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}

Run results

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/80/5E/wKioL1c-wqGyjsCfAACYrSnKzz0480.png "title=" QQ picture 20160520154917.png "alt=" Wkiol1c-wqgyjscfaacyrsnkzz0480.png "/>

This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1775429

Java Network Programming Fundamentals (ii)--TCP/IP-based socket 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.