
HelloZK
V1
2021/05/18阅读:53主题:自定义主题1
Java网络编程
InetAddress类
-
JDK中提供了一个与IP地址相关的InetAddress类,用于封装一个IP地址,并提供相关方法。
import java.net.InetAddress;
public class Example {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("本机的IP地址:" + inetAddress.getHostAddress());
InetAddress remoteAddress = InetAddress.getByName("www.baidu.com");
System.out.println("百度的IP地址:" + remoteAddress.getHostAddress());
System.out.println("3秒是否可达:" + remoteAddress.isReachable(3000));
System.out.println("百度的主机名为:" + remoteAddress.getHostName());
}
}
UDP通信「面向无连接的协议」
-
UDP通信的接收端
import java.net.*;
public class Receiver {
public static void main(String[] args) throws Exception{
byte[] buf = new byte[1024];
DatagramSocket socket = new DatagramSocket(8899);
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("等待接受数据");
socket.receive(packet); //等待接收数据,如果没有数据就会堵塞
String str = new String(packet.getData(), 0, packet.getLength())
+ "from "+packet.getAddress().getHostAddress()+":"+packet.getPort();
System.out.println(str);
socket.close();
}
}
-
UDP通信的发送端
import java.net.*;
public class Sender {
public static void main(String[] args) throws Exception {
byte[] data = "Hello world!".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), 8899);
DatagramSocket socket = new DatagramSocket(9988);
System.out.println("发送消息");
socket.send(packet);
socket.close();
}
}
TCP通信
-
TCP通信的服务端
import java.io.OutputStream;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
new TCPServer().listen();
}
}
class TCPServer{
private static final int PORT = 7788;
public void listen() throws Exception {
ServerSocket socket = new ServerSocket(PORT);
Socket client = socket.accept();
OutputStream outs = client.getOutputStream();
System.out.println("开始与客户端交互数据");
outs.write("Hello world!".getBytes());
Thread.sleep(5000);
System.out.println("结束与客户端交互数据");
outs.close();
client.close();
}
}
-
TCP通信的客户端
import java.io.InputStream;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
new TCPClient().connect();
}
}
class TCPClient{
private static final int PORT = 7788;
public void connect() throws Exception {
Socket client = new Socket(InetAddress.getLocalHost(), PORT);
InputStream ins = client.getInputStream();
byte[] buf = new byte[1024];
int len = ins.read(buf);
System.out.println(new String(buf,0,len));
client.close();
}
}
作者介绍

HelloZK
V1