java网络编程
网络编程指在多个设备间执行的程序,设备之间用网络互相连接起来。
java.net包中提供两种通用的网络协议:
- TCP:Transmission Control Protocol 允许两个应用之间进行通信。TCP协议在IP协议中广泛应用,称为TCP/IP。
- UDP:User Datagram Protocol 允许应用之间数据包的传输。
Socket编程
用户程序在通讯终端创建一个socket,并尝试用该socket连接一个服务器。当连接连通时,服务器在其通讯终端创建一个socket,用户与服务器可通过socket的读写进行通信。
java.net.Socket类表示一个socket,java.net.ServerSocket类为服务器程序提供用来监听用户程序,并与用户程序建立连接的机制。
ServerSocket类:
java.net.Server.Socket类用于服务器程序获取端口,并监听用户。
构造函数:
- public ServerSocket(int port) throws IOException:创建server socket,将其绑定到端口port。
- public ServerSocket(int port, int backlog) throws IOException:backlog为用户的个数。
- public ServerSocket(int port, int backlog, InetAddress address) throws IOException:由于服务器可能有多个IP地址,InetAddress用于指定用户将要连接的IP地址。
- public ServerSocket() throws IOException:创建没有绑定端口的server socket, 需要使用bind()方法来绑定端口。
方法:
- public int getLocalPort():获取服务器监听的端口,如果在构造函数中将端口值设为0,那么该方法将自动为你找到一个端口号。
- public Socket accept() throws IOException:等待用户,该方法处阻塞状态直到用户连接到服务器或者socket的计时结束。使用setSoTimeout()方法设定等待时间,否则accept()将无限期等待。返回一个socket对象。
- public void setSoTimeout(int timeout):设定等待时间
- public void bind(SocketAddress host, int backlog):用SocketAddress对象,将socket绑定到特定server与端口。与ServerSocket()配套使用。
当服务器接收到用户的连接后,服务器将创建一个新的socket与用户的socket进行通信。
Socket类:
用于用户与服务器间进行通信的socket。用户自己创建socket,而服务器使用accept()返回的socket。
构造函数:
- public Socket(String host, int port) throws UnknownHostException, IOException.:如果没有抛出异常,则用户与服务器的连接建立成功。
- public Socket(InetAddress host, int port) throws IOException:host由其网络地址表
- public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.:在特定地址创建当前主机的socket
- public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
- public Socket():创建一个未连接的socket。
当socket构造函数返回时,不仅仅初始化了一个socket对象,还连接到了特定的服务器与端口。
方法:
- public void connect(SocketAddress host, int timeout) throws IOException:只有使用Socket()时使用
- public InetAddress getInetAddress():获取socket的网络地址
- public int getPort():获取远程设备的端口
- public int getLocalPort():获取当前设备的端口
- public SocketAddress getRemoteSocketAddress():获取远程设备的socket地址
- public InputStream getInputStream() throws IOException:返回输入流
- ublic OutputStream getOutputStream() throws IOException:返回输出流
- public void close() throws IOException:关闭socket
InetAddress类:
- static InetAddress getByAddress(byte[] addr):根据IP地址返回InetAddress对象
- static InetAddress getByAddress(String host, byte[] addr):根据主机名和IP地址返回InetAddress
- static InetAddress getByName(String host):根据主机名,返回IP地址
- String getHostAddress():返回IP地址字符串
- static InetAddress InetAddress getLocalHost():返回当前主机
- String toString()
Socket客户端程序实例:
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("Connecting to " + serverName + " on port " + port);
//创建连接主机名为“serverName”,端口号为port的用户socket
Socket client = new Socket(serverName, port);
//当产生连接后,获取远程主机地址+端口号
System.out.println("Just connected to " + 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("Server says " + in.readUTF());
client.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Socket Server实例:
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("Waiting for client on port " + serverSocket.getLocalPort() + "...");
//开始监听用户,若获取用户,返回新的服务器socket对象
Socket server = serverSocket.accept();
//监听到用户,与用户连接后获取用户地址+端口
System.out.println("Just connected to " + 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 to " + 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.start();
} catch (IOException e)
{
e.printStackTrace();
}
}
}