亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java利用套接字實(shí)現(xiàn)應(yīng)用程序?qū)?shù)據(jù)庫(kù)的訪問(wèn)

 更新時(shí)間:2022年09月19日 16:37:34   作者:JaydenChang  
所謂套接字(Socket),就是對(duì)網(wǎng)絡(luò)中不同主機(jī)上的應(yīng)用進(jìn)程之間進(jìn)行雙向通信的端點(diǎn)的抽象。這篇文章主要介紹了Java利用套接字實(shí)現(xiàn)應(yīng)用程序?qū)?shù)據(jù)庫(kù)的訪問(wèn),感興趣的可以了解一下

前言

最近在完成軟件體系結(jié)構(gòu)上機(jī)實(shí)驗(yàn)時(shí),遇到一個(gè)有點(diǎn)點(diǎn)小難度的選做題,題目信息如下:

利用套接字技術(shù)實(shí)現(xiàn)應(yīng)用程序中對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)。應(yīng)用程序只是利用套接字連接向服務(wù)器發(fā)送一個(gè)查詢的條件,而服務(wù)器負(fù)責(zé)對(duì)數(shù)據(jù)庫(kù)的查詢,然后服務(wù)器再將查詢的結(jié)果利用建立的套接字返回給客戶端,如下圖所示。

本來(lái)吧,選做題,不太想做的,但是考慮到以后工作的方向和后端相關(guān),那還是做吧。

本次實(shí)驗(yàn)需要做一個(gè)GUI界面和一個(gè)連接查詢功能,在論壇上借鑒了其他大佬獲取網(wǎng)站內(nèi)容的部分代碼,然后自己做了一個(gè)及其簡(jiǎn)陋的swing界面,算是把這個(gè)實(shí)驗(yàn)完成了。

本次實(shí)驗(yàn)項(xiàng)目結(jié)構(gòu)如下

--socketProject
    |--Client.java
    |--GUI.java
    |--SearchInfo.java
    |--Server.java
    |--ServerThread.java

Client.java

客戶端使用dis.readUTF()時(shí),要注意再發(fā)送個(gè)字符或者空字符,這里發(fā)送end,表示關(guān)閉連接。不然會(huì)出現(xiàn)EOFException

package socketProject;

import java.io.*;
import java.net.*;

public class Client {
    String studentNum = null;
    String result = null;

    public void setStudentNum(String num) {
        this.studentNum = num;
        System.out.println("stu: " + studentNum);
    }

    public void run() throws IOException {
        Socket ss = new Socket("127.0.0.1", 8888);
        System.out.println("Socket: " + ss);
        try {
            DataInputStream dis = new DataInputStream(ss.getInputStream());
            DataOutputStream dos = new DataOutputStream(ss.getOutputStream());
            // the interaction
            dos.writeUTF(studentNum); // 向服務(wù)器發(fā)送學(xué)號(hào)
            dos.flush();
            result = dis.readUTF().toString(); // 獲得客戶端的json字符串
            System.out.println(result);
            dos.writeUTF("end"); // 不加這句會(huì)報(bào)錯(cuò)
            dos.flush();
            if (dos != null)
                dos.close();
            if (dis != null)
                dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ss != null)
                ss.close();
        }
    }
	// gui界面用于獲取json結(jié)果
    public String getResult() {
        return result;
    }
}

Server.java

package socketProject;

import java.io.*;
import java.net.*;

public class Server extends Thread {
    public static final int PORT = 8888;

    // public static void main(String[] args) throws IOException {
    public void run() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("ServerSocket: " + serverSocket);
            try {
                while (true) {
                    Socket socket = serverSocket.accept();
                    System.out.println("Socket accept: " + socket);
                    Thread thread = new Thread(new ServerThread(socket));
                    thread.start(); // 開(kāi)啟一個(gè)線程,使之支持接收多個(gè)客戶端的請(qǐng)求
                }
            } finally {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ServerThread.java

package socketProject;

import java.io.*;
import java.net.*;

public class ServerThread extends Thread {
    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            while (true) {
                String str = dis.readUTF().toString();
                String data = new SearchInfo().run(str);
                if (str.equals("end"))
                    break;

                dos.writeUTF(data);
            }
            dos.close();
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

SearchInfo.java

package socketProject;

import java.io.*;
import java.net.*;

public class SearchInfo {
    public String run(String s) {
        String url = "your database interface";
        String param = s;
        String sendGET = GetUrl(url, param);
        return sendGET;
    }
    
    public static String GetUrl(String url, String param) {
        String result = ""; // define the result str
        BufferedReader read = null; // define the access result
        
        try {
            URL realUrl = new URL(url + param);
            URLConnection connection = realUrl.openConnection();
            
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 這里補(bǔ)充通用的請(qǐng)求屬性
            connection.connect(); // 建立實(shí)際的連接
            
            read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = read.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (read != null) {// 關(guān)閉流
                try {
                    read.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    
    public String getJSON(String param) {
        return param;
    }
}

GUI.java

package socketProject;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;

public class GUI extends JFrame {
    private JButton connectDataBase;
    private JLabel entryStudentNum;
    private JTextField studentNum;
    private JButton sendRequest;
    private JLabel showResponseMsg;
    private JPanel northPanel;
    private JPanel southPanel;

    public GUI() {
        init();
    }

    public void init() {
        setTitle("沒(méi)啥技術(shù)含量的東西");
        // define the component for the window
        connectDataBase = new JButton("連接數(shù)據(jù)庫(kù)");
        entryStudentNum = new JLabel("輸入學(xué)號(hào)");
        studentNum = new JTextField();
        sendRequest = new JButton("發(fā)送");
        showResponseMsg = new JLabel();

        // add the component to the panel
        this.setLayout(new GridLayout(2, 1));

        northPanel = new JPanel(new GridLayout(1, 4));

        northPanel.add(connectDataBase);
        northPanel.add(entryStudentNum);
        northPanel.add(studentNum);
        northPanel.add(sendRequest);

        southPanel = new JPanel(new GridLayout(1, 1));

        southPanel.add(showResponseMsg);

        setButtons();

        this.add(northPanel);
        this.add(southPanel);
        // initial the window
        setBounds(400, 200, 600, 120);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void setButtons() {
        connectDataBase.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 這里初始化服務(wù)端
                Server server1 = new Server();
                Thread th1 = new Thread(server1);
                th1.start();
                // 這里一定要開(kāi)啟服務(wù)端線程,否則在點(diǎn)擊此按鈕后,整個(gè)界面會(huì)卡住,無(wú)法進(jìn)行下一步操作
            }
        });

        sendRequest.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Client client1 = new Client();
                client1.setStudentNum(studentNum.getText());
                // 獲取文本框的文字,并賦給客戶端的studentNum保存
                try {
                    client1.run();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                showResponseMsg.setText(client1.getResult());
                // 將得到的數(shù)據(jù)顯示在界面上
            }
        });
    }

    public static void main(String[] args) {
        new GUI();
    }
}

最終效果如下:

使用時(shí),先點(diǎn)擊連接數(shù)據(jù)庫(kù),然后根據(jù)學(xué)校提供的接口,輸入自己的學(xué)號(hào),點(diǎn)擊發(fā)送,即可查詢個(gè)人信息。

不過(guò)由于項(xiàng)目工作區(qū)非maven以及未來(lái)方向非Java的緣故,沒(méi)有去深究如何提取json的值 (偷個(gè)懶)。

以上就是Java利用套接字實(shí)現(xiàn)應(yīng)用程序?qū)?shù)據(jù)庫(kù)的訪問(wèn) 的詳細(xì)內(nèi)容,更多關(guān)于Java套接字的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論