高级编程
Created: 2024-09-04 Wed 20:52
Socket
的网络编程。InetAddress
类import java.net.InetAddress;
public class IPHostConvertSample {
public static void main(String args[]) {
try {
InetAddress ia = InetAddress.getByName("www.ncut.edu.cn");
String ip = ia.getHostAddress(); // IP address
String hostname = ia.getHostName(); // Hostname
System.out.println("IP address: " + ip);
System.out.println("Hostname: " + hostname);
} catch (Exception e) {
e.printStackTrace();
}
}
}
IP address: 202.204.24.39 Hostname: www.ncut.edu.cn
Socket
的网络编程
// Server.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
int number = 0;
// 指定服务器监听的端口号,需和客户端中一致
ServerSocket serverSocket = new ServerSocket(3456);
System.out.println("Running...");
while(true) {
// 服务器监听客户端连接,阻塞方法
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream(); // 服务器接收数据
byte b[] = new byte[1024];
int len = is.read(b);
System.out.print("(Length: " + len + ") ");
String s = new String(b, 0, len);
System.out.println("Message from client: " + s);
OutputStream os = socket.getOutputStream(); // 服务器发送数据
String sendStr = "Hi there #" + number++;
os.write(sendStr.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Client.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
// 创建一个套接字对象,第一个参数填写服务器的ip地址,第二个参数填写服务器的端口号
Socket socket = new Socket("localhost", 3456);
OutputStream os = socket.getOutputStream(); // 向服务器发送数据
String inputStr = "Hi";
if (args.length == 1) { inputStr = args[0]; }
os.write(inputStr.getBytes());
InputStream is = socket.getInputStream(); // 从服务器接收数据
byte b[] = new byte[1024];
int len = is.read(b);
String s = new String(b, 0, len);
System.out.println("Message from server: " + s);
is.close(); // 关闭输入流
os.close(); // 关闭输出流
socket.close(); // 关闭套接字
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Message from server: Hi there #17
Figure 1: How many bytes per character in utf-8 \(^{*}\)
\(*\) https://www.ibm.com/docs/en/db2-for-zos/12?topic=unicode-utfs