1. 利用InetAddress编写程序接受用户输入网址,输出这个网址的主机IP地址。
package project;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class GetIPAddress {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入网址: ");String hostname = scanner.nextLine();try {InetAddress address = InetAddress.getByName(hostname);String ipAddress = address.getHostAddress();System.out.println("网址的主机IP地址是: " + ipAddress);} catch (UnknownHostException e) {System.out.println("无法解析该网址的主机IP地址。");}}
}
2. 利用Socket编写一个服务器端程序和一个客户端程序,要求服务器端程序运行后监听指定端口,检测到客户端程序连接并发来数据后,服务器端对该数据进行处理并传回客户端一段信息。
Server.java
package project;
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) {int port = 8000;try {ServerSocket serverSocket = new ServerSocket(port);System.out.println("服务器已启动,正在监听端口 " + port);while (true) {Socket clientSocket = serverSocket.accept();System.out.println("客户端已连接,来自 " + clientSocket.getInetAddress());// 处理客户端请求handleClientRequest(clientSocket);}} catch (IOException e) {e.printStackTrace();}}private static void handleClientRequest(Socket clientSocket) throws IOException {// 获取输入流和输出流InputStream inputStream = clientSocket.getInputStream();OutputStream outputStream = clientSocket.getOutputStream();// 读取客户端数据byte[] buffer = new byte[1024];int bytesRead = inputStream.read(buffer);String requestData = new String(buffer, 0, bytesRead);System.out.println("接收到客户端数据: " + requestData);// 对客户端数据进行处理String responseData = "服务器已收到你的消息";byte[] responseBuffer = responseData.getBytes();// 向客户端发送响应数据outputStream.write(responseBuffer);outputStream.flush();// 关闭资源inputStream.close();outputStream.close();clientSocket.close();System.out.println("连接已关闭");}
}
Client.java
package project;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {public static void main(String[] args) {String serverAddress = "127.0.0.1";int serverPort = 8000;try {Socket socket = new Socket(serverAddress, serverPort);// 发送数据到服务器String requestData = "Hello, Server!";byte[] requestBuffer = requestData.getBytes();OutputStream outputStream = socket.getOutputStream();outputStream.write(requestBuffer);outputStream.flush();System.out.println("发送数据到服务器: " + requestData);// 接收服务器响应InputStream inputStream = socket.getInputStream();byte[] responseBuffer = new byte[1024];int bytesRead = inputStream.read(responseBuffer);String responseData = new String(responseBuffer, 0, bytesRead);System.out.println("收到服务器响应: " + responseData);// 关闭资源inputStream.close();outputStream.close();socket.close();} catch (IOException e) {e.printStackTrace();}}
}
3. 安装并配置MySQL数据库,并准备好JDBC所需驱动(相关程序可从:课件资料/工具 的目录下载)。利用SQL语句创建“JDBCTest”库、“website”表。其中,要求“website”表至少含有如下字段:name(站点名称,字符型)、alexa(Alexa排名,整型)、country(所属国家字符型)。
4. 利用JDBC编程,向website表中增添数据。利用JDBC编程,获取website表的所有数据并输出。
package project;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class MySQLTest {
String databaseName="jdcbtest";//数据库名String user = "root";//使用管理员账号启动String pwd = "123";//数据库密码String URL = "jdbc:mysql://localhost:3306/"+databaseName+"?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false";String DRIVER = "com.mysql.jdbc.Driver";public static void main(String[] args) {MySQLTest myJDBC = new MySQLTest();myJDBC.connect();}public void connect() {Connection connection = null;Statement statement = null;try {Class.forName(DRIVER);connection = DriverManager.getConnection(URL, user, pwd);statement = connection.createStatement();int count_insert = statement.executeUpdate("INSERT INTO website VALUES ('lihua','1','china');");System.out.println("插入" + count_insert + "条记录");String query = "SELECT * FROM website;";ResultSet resultSet = statement.executeQuery(query);//展开结果集数据库int i = 0;while (resultSet.next()) {// 通过字段检索String name = resultSet.getString("name");int alexa = resultSet.getInt("alexa");String country = resultSet.getString("country");// 输出数据System.out.println("第" + (++i) + "的数据为:");System.out.println("name: " + name);System.out.println("alexa: " + alexa);System.out.println("country: " + country);}resultSet.close();statement.close();connection.close();} catch (SQLException | ClassNotFoundException e) {e.printStackTrace();} finally {try {if (statement != null)statement.close();if(connection!=null)connection.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}}
5. 利用2-4题内容,将第2题的服务器改写升级,使之可以保存客户端的发来的数据。(提示:可以按需要保存数据,自行设计服务器端相关表结构)
Server.java
package project;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class Server {public static void main(String[] args) {int port = 12345;try (ServerSocket serverSocket = new ServerSocket(port)) {System.out.println("Server listening on port " + port);while (true) {try (Socket clientSocket = serverSocket.accept();InputStream inputStream = clientSocket.getInputStream();OutputStream outputStream = clientSocket.getOutputStream()) {// 读取客户端发送的数据byte[] buffer = new byte[1024];int bytesRead = inputStream.read(buffer);String clientData = new String(buffer, 0, bytesRead);// 处理数据并保存到数据库saveDataToDatabase(clientData);// 打印所有数据printAllDataFromDatabase();// 发送回应给客户端String response = "Server received data: " + clientData;outputStream.write(response.getBytes());} catch (IOException e) {e.printStackTrace();} catch (Exception e) {throw new RuntimeException(e);}}} catch (IOException e) {e.printStackTrace();}}private static void saveDataToDatabase(String data)throws Exception {// 数据库连接信息Class.forName("com.mysql.jdbc.Driver");String jdbcUrl = "jdbc:mysql://localhost:3306/JDBCTest";String user = "root";String password = "123";try (Connection connection = DriverManager.getConnection(jdbcUrl, user, password)) {// 插入数据的SQL语句String insertQuery = "INSERT INTO client_data (data) VALUES (?)";try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {preparedStatement.setString(1, data);preparedStatement.executeUpdate();}} catch (SQLException e) {e.printStackTrace();}}private static void printAllDataFromDatabase() throws Exception{// 数据库连接信息Class.forName("com.mysql.cj.jdbc.Driver");String jdbcUrl = "jdbc:mysql://localhost:3306/JDBCTest";String user = "root";String password = "12345";try (Connection connection = DriverManager.getConnection(jdbcUrl, user, password)) {// 查询所有数据的SQL语句String selectQuery = "SELECT * FROM client_data";try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery);ResultSet resultSet = preparedStatement.executeQuery()) {// 打印查询结果System.out.println("All data in client_data table:");while (resultSet.next()) {int id = resultSet.getInt("id");String data = resultSet.getString("data");System.out.println("ID: " + id + ", Data: " + data);}System.out.println();}} catch (SQLException e) {e.printStackTrace();}}
}
Client.java
package project;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Client {public static void main(String[] args) {String serverHost = "localhost";int serverPort = 12345;try (Socket socket = new Socket(serverHost, serverPort);OutputStream outputStream = socket.getOutputStream();InputStream inputStream = socket.getInputStream()) {// 获取当前时间并格式化SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String currentTime = dateFormat.format(new Date());// 发送带有时间的数据给服务器String dataToSend = "Hello, Server! " + currentTime;outputStream.write(dataToSend.getBytes());// 接收服务器的回应byte[] buffer = new byte[1024];int bytesRead = inputStream.read(buffer);String serverResponse = new String(buffer, 0, bytesRead);System.out.println("Server response: " + serverResponse);} catch (IOException e) {e.printStackTrace();}}
}