Java Network programming

Source: Internet
Author: User

Java Network Programming

Network programming refers to writing programs that run on multiple devices (computers) that are connected through the network.

The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without focusing on the details of the communication.

The java.net package provides support for two common network protocols:

TCP:TCP 是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信。通常用于互联网协议,被称 TCP / IP。UDP:UDP 是用户数据报协议的缩写,一个无连接的协议。提供了应用程序之间要发送的数据的数据包。

This tutorial focuses on the following two topics.

Socket 编程:这是使用最广泛的网络概念,它已被解释地非常详细。URL 处理:这部分会在另外的篇幅里讲,点击这里更详细地了解在 Java 语言中的 URL 处理。

Socket programming

Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and tries to connect to the server's socket.

When the connection is established, the server creates a Socket object. The client and server can now communicate by writing and reading to the Socket object.

The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a mechanism for the server program to listen to the client and establish a connection with them.

The following steps occur when a TCP connection is established between two computers using sockets:

服务器实例化一个 ServerSocket 对象,表示通过服务器上的端口通信。服务器调用 ServerSocket 类的 accept() 方法,该方法将一直等待,直到客户端连接到服务器上给定的端口。服务器正在等待时,一个客户端实例化一个 Socket 对象,指定服务器名称和端口号来请求连接。Socket 类的构造函数试图将客户端连接到指定的服务器和端口号。如果通信被建立,则在客户端创建一个 Socket 对象能够与服务器进行通信。在服务器端,accept() 方法返回服务器上一个新的 socket 引用,该 socket 连接到客户端的 socket。

After the connection is established, each socket has an output stream and an input stream by using the I/O stream, and the client's output is streamed to the server-side input stream, and the client's input is streamed to the server-side output stream.

TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. Here are some classes that provide a complete set of useful ways to implement a socket.
Methods of the ServerSocket class

The server application obtains a port by using the Java.net.ServerSocket class and listens for client requests.

The ServerSocket class has four methods of construction:
Ordinal method Description
1 public serversocket (int port) throws IOException
Creates a server socket bound to a specific port.
2 public serversocket (int port, int backlog) throws IOException
Creates a server socket with the specified backlog and binds it to the specified local port number.
3 public serversocket (int port, int backlog, inetaddress address) throws IOException
Creates a server using the specified port, the listener backlog, and the local IP address to bind to.
4 public ServerSocket () throws IOException
Create a non-binding server socket.

Create a non-binding server socket. If the ServerSocket constructor method does not throw an exception, it means that your application has successfully bound to the specified port and listens for client requests.

Here are some common methods for ServerSocket classes:
Ordinal method Description
1 public int Getlocalport ()
Returns the port on which this socket listens.
2 public Socket Accept () throws IOException
Listens for and accepts connections to this socket.
3 public void Setsotimeout (int timeout)
Enables/disables so_timeout, in milliseconds, by specifying a time-out value.
4 public void bind (socketaddress host, int backlog)
Bind the ServerSocket to a specific address (IP address and port number).
Method of Socket Class

The Java.net.Socket class represents a socket that both the client and the server use to communicate with each other. The client wants to get a socket object by instantiating it, and the server obtains a socket object through the Accept () method's return value.

The Socket class has five constructor methods.
Ordinal method Description
1 public Socket (String host, int port) throws Unknownhostexception, IOException.
Creates a stream socket and connects it to the specified port number on the specified host.
2 Public Socket (inetaddress host, int port) throws IOException
Creates a stream socket and connects it to the specified port number for the specified IP address.
3 Public sockets (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 sockets (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 sockets ()
Create an SocketImpl socket from the system default type

When the socket construction method returns, and does not simply instantiate a socket object, it will actually attempt to connect to the specified server and port.

Here are some interesting ways to note that both the client and server side have a Socket object, so the methods can be invoked both by the client and the service side.
Ordinal method Description
1 public void Connect (socketaddress host, int timeout) throws IOException
Connect this socket to the server and specify a timeout value.
2 public inetaddress getinetaddress ()
Returns the address of the socket connection.
3 public int getport ()
Returns the remote port that this socket is connected to.
4 public int getlocalport ()
Returns the local port to which this socket is bound.
5 public socketaddress getremotesocketaddress ()
Returns the address of the endpoint for this socket connection, or null if not connected.
6 Public InputStream getInputStream () throws IOException
returns the input stream for this socket.
7 public OutputStream Getoutputstream () throws IOException
returns the output stream for this socket.
8 public void Close () throws IOException
closes the socket.
Methods of the InetAddress class

This class represents an Internet Protocol (IP) address. The following is a list of the more useful methods for Socket programming:
Ordinal method Description
1 static inetaddress getbyaddress (byte[] addr)
Returns the InetAddress object, given the original IP address.
2 static inetaddress getbyaddress (String host, byte[] addr)
Creates a inetaddress based on the host name and IP address provided.
3 static inetaddress Getbyname (String host)
Determines the IP address of the host in the given host name.
4 String gethostaddress ()
Returns the IP address string (in text representation).
5 String GetHostName ()
Gets the host name for this IP address.
6 static inetaddress Getlocalhost ()
Returns the local host.
7 String toString ()
Convert this IP address to a String.
Socket Client Instance

The following greetingclient is a client program that connects to the server via the socket and sends a request, and then waits for a response.
Greetingclient.java File Code:
File name 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 ("Connect to Host:" + ServerName + ", port number:" + port);
Socket client = new socket (serverName, port);
SYSTEM.OUT.PRINTLN ("Remote host Address:" + 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();  }

}
}
Socket Service-side instance

The Greetingserver program below is a server-side application that uses a Socket to listen on a specified port.
Greetingserver.java File Code:
File name 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 ("Wait for remote connection, port number:" + serversocket.getlocalport () + "...");
Socket Server = Serversocket.accept ();
SYSTEM.OUT.PRINTLN ("Remote host Address:" + server.getremotesocketaddress ());
DataInputStream in = new DataInputStream (Server.getinputstream ());
System.out.println (In.readutf ());
DataOutputStream out = new DataOutputStream (Server.getoutputstream ());
Out.writeutf ("Thank You for connecting me:" + 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 ();
}
}
}

Compile the above two Java file code and execute the following command to start the service with a port number of 6066:

$ Javac Greetingserver.java
$ java greetingserver 6066
To wait for a remote connection, the port number is: 6066 ...

Open a new command window and execute the above command to open the client:

$ Javac Greetingclient.java
$ java greetingclient localhost 6066
Connect to host: localhost, port number: 6066
Remote Host Address: localhost/127.0.0.1:6066
Server response: Thank you for connecting me:/127.0.0.1:6066
goodbye!

Java Network 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.