提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
网络编程
- TCP/IP
- UDP
TCP
测试:InetAddress
public class TestInetAddress {
public static void main(String[] args) {
// 查询本机ip
try {
InetAddress inet1 = InetAddress.getByName("127.0.0.1");
System.out.println(inet1);
InetAddress inet2 = InetAddress.getByName("localhost");
System.out.println(inet2);
InetAddress inet3 = InetAddress.getLocalHost();
System.out.println(inet3);
// 查询网站ip
InetAddress byName = InetAddress.getByName("www.baidu.com");
System.out.println(byName);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
测试 InetSocketAddress
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
InetSocketAddress address1 = new InetSocketAddress("localhost", 8080);
System.out.println(address);
System.out.println(address1);
System.out.println(address.getAddress());
System.out.println(address.getHostName()); // 获得地址
System.out.println(address.getPort()); // 获得端口号
}
}
客户端与服务端通信
客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
// 1.要知道服务端的 ip 和 端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9898;
// 2.创建一个连接
socket = new Socket(serverIP, port);
// 3.发送消息, IO流
os = socket.getOutputStream();
os.write("你好,欢迎学习Java!".getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
服务端
public class TcpServerDemo01 {
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
try {
// 1.我得有一个地址
serverSocket = new ServerSocket(9898);
while (true) {