Getting Started with Java - Advanced Tutorial - 05. Network Programming

Original Address: http://www.work100.net/training/java-networking.html
More Tutorials: beam cloud - free course

network programming

No. Article section video
1 Outline
2 Socket Programming
3 The method of ServerSocket
4 Socket class method
5 InetAddress class method
6 Socket client instances
7 Socket server instance

Please refer above 章节导航to read

1 Overview

Network programming means programs written to run on a plurality of devices (computers) of these devices are connected through a network.

java.netJ2SE package contains an API classes and interfaces that provide low-level details of the communication. You can use these classes and interfaces to focus on solving problems, rather than focus on communication details.

java.net Package provides support for two common network protocols:

  • The TCP : TCPis an abbreviation for Transmission Control Protocol, which guarantees reliable communication between the two applications. Commonly used Internet protocol, is called TCP / IP.
  • The UDP : UDPis an abbreviation of User Datagram Protocol, a connectionless protocol. Providing the packet data to be sent between applications.

This tutorial explains the following two topics.

  • Socket Programming : This is the most widely used networking concepts, it has to be interpreted very detailed.

  • URL Handling : This section will speak in another space here, click here to learn the Java language in more detail URLprocessing

2.Socket Programming

Use socket TCPprovides a communication mechanism between the two computers. The client program creates a socket and trying to connect to the server socket.

When the connection is established, the server creates an Socketobject. The client and server can now to Socketcommunicate in writing and reading the object.

java.net.SocketClass represents a socket, and the java.net.ServerSocketclass provides a server to listen for client programs and mechanisms connected with them.

Use the following steps to establish a socket between two computers TCPoccurs when the connection:

  • Instantiating a server ServerSocketobject that represents a communication port on the server by
  • Server calls the ServerSocketclass accept()method will wait until a client connects to the server on a given port
  • When the server is waiting for a client to instantiate an Socketobject that specifies the server name and port number to request a connection
  • SocketClass constructor try to connect a client to the server and port number specified. If the communication is established, it creates a client Socketobject is able to communicate with the server
  • On the server side, accept()the method returns a new server socketreferences, which socketare connected to the clientsocket

After the connection is established, by using a I/Oflow communication is performed, each sockethas a stream and a stream output, output input stream client to server input stream, the input stream to the client server output stream.

TCPIt is a two-way communication protocol, so that the data stream can be transmitted at the same time by the two data. The following are some of the class to provide a complete set of useful methods to achieve socket.

Class method 3.ServerSocket

The server application by using java.net.ServerSocketthe class to get a port, and listens for client requests.

ServerSocket There are four class constructor:

No. The method described
1 public ServerSocket(int port) throws IOException
Create a server socket on a specified port.
2 public ServerSocket(int port, int backlog) throws IOException
With the specified backlogcreate a server socket and binds it to a local port number specified.
3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Using the specified port, listen backlogand to bind to the local IPcreate server address.
4 public ServerSocket() throws IOException
Creates an unbound server socket.

Creates an unbound server socket. If ServerSocketthe constructor does not throw an exception, it means that your application has been successfully bound to the specified port and listens for client requests.

Here are some ServerSocketcommonly used methods of the class:

No. The method described
1 public int getLocalPort()
Returns the port on which this socket is listening.
2 public Socket accept() throws IOException
Listening and accepting connections to this socket.
3 public void setSoTimeout(int timeout)
Enable specified timeout / disable SO_TIMEOUT, in milliseconds.
4 public void bind(SocketAddress host, int backlog)
It will ServerSocketbind to a specific address ( IP地址and 端口号).

Class method 4.Socket

java.net.SocketClass behalf of the client and server socket used to communicate with each other. To get a client Socketobject is instantiated by, the server obtains a Socketsubject through accept()the return value.

Socket There are five class constructor.

No. The method described
1 public Socket(String host, int port) throws UnknownHostException, IOException
Creates a stream socket and connect it to the specified 主机designated on 端口号.
2 public Socket(InetAddress host, int port) throws IOException
Creates a stream socket and connects it to the specified IP地址designation 端口号.
3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
Creates a socket and connects it to the specified remote port on the specified remote host.
4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException
Creates a socket and connects it to the specified remote port on the specified remote address.
5 public Socket()
By default type SocketImplis not connected to create a socket

When the Socketconstructor returns, and not a simple example of an Socketobject, it actually tries to connect to the server and the specified port.

下面列出了一些感兴趣的方法,注意客户端和服务器端都有一个 Socket 对象,所以无论客户端还是服务端都能够调用这些方法。

序号 方法描述
1 public void connect(SocketAddress host, int timeout) throws IOException
将此套接字连接到服务器,并指定一个超时值。
2 public InetAddress getInetAddress()
返回套接字连接的地址。
3 public int getPort()
返回此套接字连接到的远程端口。
4 public int getLocalPort()
返回此套接字绑定到的本地端口。
5 public SocketAddress getRemoteSocketAddress()
返回此套接字连接的端点的地址,如果未连接则返回 null
6 public InputStream getInputStream() throws IOException
返回此套接字的输入流。
7 public OutputStream getOutputStream() throws IOException
返回此套接字的输出流。
8 public void close() throws IOException
关闭此套接字。

5.InetAddress类的方法

这个类表示互联网协议(IP)地址。下面列出了 Socket 编程时比较有用的方法:

序号 方法描述
1 static InetAddress getByAddress(byte[] addr)
在给定原始 IP 地址的情况下,返回 InetAddress 对象。
2 static InetAddress getByAddress(String host, byte[] addr)
根据提供的主机名和 IP 地址创建 InetAddress
3 static InetAddress getByName(String host)
在给定主机名的情况下确定主机的 IP 地址。
4 String getHostAddress()
IP 地址字符串(以文本表现形式)。
5 String getHostName()
获取此 IP 地址的主机名。
6 static InetAddress getLocalHost()
返回本地主机。
7 String toString()
将此 IP 地址转换为 String

6.Socket客户端实例

如下的 GreetingClient 是一个客户端程序,该程序通过 socket 连接到服务器并发送一个请求,然后等待一个响应。

// 文件名 GreetingClient.java
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
         Socket client = new Socket(serverName, port);
         System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
 
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("服务器响应: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

7.Socket服务端实例

如下的 GreetingServer 程序是一个服务器端应用程序,使用 Socket 来监听一个指定的端口。

// 文件名 GreetingServer.java
import java.net.*;
import java.io.*;
 
public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }
 
   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt(args[0]);
      try
      {
         Thread t = new GreetingServer(port);
         t.run();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

编译以上两个 Java 文件代码,并执行以下命令来启动服务,使用端口号6066

$ javac GreetingServer.java 
$ java GreetingServer 6066
等待远程连接,端口号为:6066...

新开一个命令窗口,执行以上命令来开启客户端:

$ javac GreetingClient.java 
$ java GreetingClient localhost 6066
连接到主机:localhost ,端口号:6066
远程主机地址:localhost/127.0.0.1:6066
服务器响应: 谢谢连接我:/127.0.0.1:6066
Goodbye!

Previous: Serialization

Next: mail

Guess you like

Origin www.cnblogs.com/liuxiaojun/p/training-java-networking.html