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.net
J2SE 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 :
TCP
is an abbreviation for Transmission Control Protocol, which guarantees reliable communication between the two applications. Commonly used Internet protocol, is calledTCP / IP
. - The UDP :
UDP
is 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
URL
processing
2.Socket Programming
Use socket TCP
provides 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 Socket
object. The client and server can now to Socket
communicate in writing and reading the object.
java.net.Socket
Class represents a socket, and the java.net.ServerSocket
class provides a server to listen for client programs and mechanisms connected with them.
Use the following steps to establish a socket between two computers TCP
occurs when the connection:
- Instantiating a server
ServerSocket
object that represents a communication port on the server by - Server calls the
ServerSocket
classaccept()
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
Socket
object that specifies the server name and port number to request a connection Socket
Class constructor try to connect a client to the server and port number specified. If the communication is established, it creates a clientSocket
object is able to communicate with the server- On the server side,
accept()
the method returns a new serversocket
references, whichsocket
are connected to the clientsocket
After the connection is established, by using a I/O
flow communication is performed, each socket
has a stream and a stream output, output input stream client to server input stream, the input stream to the client server output stream.
TCP
It 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.ServerSocket
the 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 backlog create 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 backlog and to bind to the local IP create server address. |
4 | public ServerSocket() throws IOException Creates an unbound server socket. |
Creates an unbound server socket. If ServerSocket
the 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 ServerSocket
commonly 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 ServerSocket bind to a specific address ( IP地址 and 端口号 ). |
Class method 4.Socket
java.net.Socket
Class behalf of the client and server socket used to communicate with each other. To get a client Socket
object is instantiated by, the server obtains a Socket
subject 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 SocketImpl is not connected to create a socket |
When the Socket
constructor returns, and not a simple example of an Socket
object, 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