Java Socket Network Programming Basics Introduction Tutorial _java

Source: Internet
Author: User

Introduction of TCP/IP

The TCP/IP protocol family is a protocol used by the Internet and can also be used in a separate private network.
The TCP/IP protocol family includes IP protocol, TCP protocol and UDP protocol.

IP protocol uses IP address to distribute packets, but it is the best service, the message may be lost, disorderly or
Repeatedly sent. TCP and UDP protocols add the port number on the basis of IP protocol, which can be used in two host computers.
Establish a transparent connection between programs.

The difference is that the TCP protocol fixes an IP layer error that creates a connection between the hosts through a handshake message.
The error in the message is then recovered by adding a serial number to the message. and UDP simply expands the IP protocol,
Enables it to work between applications, not between hosts.

With respect to IP addresses, a host can have multiple network interfaces, and an interface can have multiple addresses.
Some IP addresses are for special purposes:

A. Loopback address: 127.0.0.1, is always assigned to a loopback interface, mainly for testing.

B. Private address: 10, 192.168, 172. (16-31) at the beginning, for the private network. NAT Device Forwarding Message
, a private address port pair of the incoming message is mapped to a public address port pair in another interface. This
Allows a small group of hosts to share an IP address pair.

C. Multicast address: The first number is between 224~239.

Second, socket base

1. Access to Addresses

public static void Main (string[] args) { 
 
  try { 
    enumeration<networkinterface> interfaces = Networkinterface.getnetworkinterfaces (); 
    while (Interfaces.hasmoreelements ()) { 
      NetworkInterface iface = Interfaces.nextelement (); 
      System.out.println ("Interface:" + iface.getname ()); 
       
      enumeration<inetaddress> addrlist = iface.getinetaddresses (); 
      if (!addrlist.hasmoreelements ()) 
        System.out.println ("No address"); 
       
      while (Addrlist.hasmoreelements ()) { 
        inetaddress address = addrlist.nextelement (); 
        SYSTEM.OUT.PRINTLN ("Address:" + address.gethostaddress ());}}} 
     
  catch (SocketException e) { 
    e.printstacktrace (); 
  } 
   
} 

2.TCP Instance Program

Note that while only a write () method is used to send a string on the client side, the server side can also
This information is accepted in multiple blocks. Even if the feedback string is stored in a block when the server returns, it is possible that the TCP
The protocol is divided into several parts.

Tcpechoclienttest.java

public static void Main (string[] args) throws IOException { 
 
  String server = args[0]; 
  byte[] data = Args[1].getbytes (); 
  int port = 7; 
   
  Socket socket = new socket (server, port); 
  System.out.println ("Connected to Server ..."); 
   
  InputStream in = Socket.getinputstream (); 
  OutputStream out = Socket.getoutputstream (); 
   
  Out.write (data); 
   
  int TOTALBYTESRCVD = 0; 
  int BYTESRCVD; 
  while (Totalbytesrcvd < data.length) { 
    if (BYTESRCVD = In.read (data, TOTALBYTESRCVD,  
        data.length- TOTALBYTESRCVD) = = = 1) 
      throw new SocketException ("Connection closed"); 
    TOTALBYTESRCVD + + bytesrcvd; 
  } 
   
  System.out.println ("Received:" + new String (data)); 
   
  Socket.close (); 
} 

Tcpechoservertest.java

private static final int bufsize =; 
 
public static void Main (string[] args) throws IOException { 
 
  ServerSocket serversocket = new ServerSocket (7); 
   
  int recvmsgsize; 
  byte[] ReceiveBuf = new Byte[bufsize]; 
  while (true) { 
    socket socket = serversocket.accept (); 
    SYSTEM.OUT.PRINTLN ("Handling Client" + 
        "from remote" + socket.getremotesocketaddress () +  
        "in local" + socket. Getlocalsocketaddress ()); 
     
    InputStream in = Socket.getinputstream (); 
    OutputStream out = Socket.getoutputstream (); 
     
    while ((Recvmsgsize = In.read (receivebuf))!=-1) { 
      out.write (receivebuf, 0, recvmsgsize); 
    } 
    Socket.close (); 
  } 
   
 

Note When the new socket specifies a port number that the remote server listens on without specifying a local port, the
Take the default address and the available port number. The client port on my machine is 4593, connected to the server's
Port 7.


3.UDP Instance Program

Why use the UDP protocol? If the application exchanges only a small amount of data, the TCP connection is established at least
The amount of information to be transferred twice (twice times the round-trip time).

Udpechoclienttest.java

public static void Main (string[] args) throws IOException {inetaddress serveraddress = Inetaddress.getbyname (args[0 
  ]); 
   
  byte[] Bytestosend = Args[1].getbytes (); 
  Datagramsocket socket = new Datagramsocket (); 
   
  Socket.setsotimeout (3000); 
   
  Datagrampacket sendpacket = new Datagrampacket (Bytestosend, Bytestosend.length, serveraddress, 7); 
   
  Datagrampacket receivepacket = new Datagrampacket (new Byte[bytestosend.length), bytestosend.length); 
  Packets May is lost, so we have to keep trying int tries = 0; 
  Boolean receivedresponse = false; 
    do {socket.send (sendpacket); 
      try {socket.receive (receivepacket); 
      if (!receivepacket.getaddress (). Equals (serveraddress)) throw new IOException ("Receive from unknown Source"); 
    Receivedresponse = true; 
      catch (IOException e) {tries++; 
    System.out.println ("Timeout, try Again"); } while (!receivedresponse && tries < 5);
   
  if (receivedresponse) System.out.println ("Received:" + New String (Receivepacket.getdata ()); 
   
  else System.out.println ("No response"); 
Socket.close (); 

 }

Udpechoservertest.java

private static final int echomax = 255;  
 
public static void Main (string[] args) throws IOException { 
 
  datagramsocket socket = new Datagramsocket (7); 
  Datagrampacket packet = new Datagrampacket (new Byte[echomax), Echomax); 
   
  while (true) { 
    socket.receive (packet); 
    SYSTEM.OUT.PRINTLN ("Handling client at" + packet.getaddress ()); 
     
    Socket.send (packet); 
    Packet.setlength (Echomax); 
  } 
   
 

This example compares the previous TCP instances with the following differences:

A.datagramsocket does not need to specify a destination address when it is created, because UDP does not need to establish a connection, each
Data messages can be sent or received at different destination addresses.

B. If you block the wait on read () Like TCP, it will probably always block there because the UDP protocol is just
Simply extend the IP protocol, the UDP message may be lost. So be sure to set the timeout time for blocking waiting.

The C.UDP protocol retains the boundary information of the message, and can receive () a maximum of one send () method at a time per receive () call
Invokes the data that is sent.

D. A UDP message datagrampacket the maximum data that can be transmitted is 65507 bytes, and the excess bytes will
is discarded automatically, and there are no prompts for the receiving program. So the cache array can be set to 65000 bytes
Right and left are safe.

E. If you repeatedly invoke the receive () method with the same Datagrampacket instance, you must explicitly reset the message's internal length to the actual length of the buffer before each call.

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.