Introduction to the basics of Socket network programming in Java

  • 2020-04-01 04:38:27
  • OfStack

I. introduction to TCP/IP

The TCP/IP protocol family is the protocol used on the Internet and can also be used on separate private networks.
The TCP/IP protocol family includes the IP protocol, TCP protocol, and UDP protocol.

The IP protocol USES IP addresses to distribute messages, but it is the best service possible and messages may be lost, out of order, or out of order
Repeat sending. TCP and UDP protocol in the IP protocol based on the port number, thus in two host applications
Transparent connections are established between programs.

Unlike TCP, which fixes bugs in the IP layer by creating connections between hosts by shaking hands,
Errors in the message are then recovered by adding a sequence number to the message. UDP simply extends the IP protocol,
Make it 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, always assigned to A loopback interface, mainly for testing.

B. Private addresses: starting with 10, 192.168, 172.(16-31) for private networks. NAT devices forward messages
, the private address port pair of a message in an interface is mapped to the public address port pair in another interface. this
Enables a small group of hosts to share an IP address pair.

C. Multicast address: the first number is between 224 and 239.

Two, Socket foundation

1. Address acquisition


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 although only a write() method is used on the Client side to send strings, the server side may also send strings from
This information is accepted in multiple blocks. Even if the feedback string is stored in a block when the server returns, it may be TCP
The protocol is split into 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 = 32; 
 
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() +  
        " at 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 that the new Socket specifies the port number that the remote server is listening for and does not specify a local port
Take the default address and available port number. On my machine the Client port is 4593, connected to the server
Port 7.


3.UDP instance program

Why use UDP? If the application exchanges only a small amount of data, the establishment phase of the TCP connection is at least
Twice as much information has to be transmitted (and twice as much 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 be 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); 
  } 
   
} 

Comparing this example with the previous TCP instance, there are the following differences:

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

B. If you block the wait on read() like TCP, you'll probably block there forever, because UDP is just
Simply extending the IP protocol, UDP messages can be lost. So be sure to set the timeout for the blocking wait.

The c.dp protocol preserves the message boundary information, and each receive() call can only receive the send() method once at most
The data sent by the invocation.

D. The maximum data that can be transmitted by a UDP DatagramPacket is 65507 bytes
It is automatically discarded, and there is no hint to the receiving program. So the cache array can be set to 65,000 bytes
Left and right are safe.

E. If the receive() method is called repeatedly using the same DatagramPacket instance, it must be explicit before each invocation
Reset the internal length of the message to the actual length of the cache.


Related articles: