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)文章
JAVA實(shí)現(xiàn)單例模式的四種方法和一些特點(diǎn)
JAVA實(shí)現(xiàn)單例模式的四種方法和一些特點(diǎn),需要的朋友可以參考一下2013-03-03java開(kāi)發(fā)中防止重復(fù)提交的幾種解決方案
我們?nèi)粘i_(kāi)發(fā)中有很多的應(yīng)用場(chǎng)景都會(huì)遇到重復(fù)提交問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于java開(kāi)發(fā)中防止重復(fù)提交的幾種解決方案,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10SpringBoot實(shí)現(xiàn)連接nacos并支持多環(huán)境部署
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)連接nacos并支持多環(huán)境部署方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06Hibernate迫切連接和普通連接的區(qū)別實(shí)例詳解
這篇文章主要介紹了Hibernate迫切連接和普通連接的區(qū)別實(shí)例詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12java實(shí)現(xiàn)表單必填參數(shù)驗(yàn)證的方法
表單校驗(yàn)是很多注冊(cè)時(shí)必做的功能, 一般我們的處理都是很粗暴的寫(xiě)個(gè)if()判斷, 然后拋異常. 本文將介紹通過(guò)代理的思想, 用注解優(yōu)雅的處理非空判斷,感興趣的一起來(lái)了解一下2021-05-05Springboot集成阿里云OSS上傳文件系統(tǒng)教程
這篇文章主要介紹了Springboot集成阿里云OSS上傳文件系統(tǒng)教程,通過(guò)詳細(xì)的圖文展示,代碼步驟的展示和文件配置信息,希望對(duì)你有所幫助2021-06-06java實(shí)現(xiàn)excel導(dǎo)出合并單元格的步驟詳解
這篇文章主要介紹了java實(shí)現(xiàn)excel導(dǎo)出合并單元格,通過(guò)使用Apache POI庫(kù),我們可以方便地創(chuàng)建Excel文件、填充數(shù)據(jù)、合并單元格和導(dǎo)出Excel文件,需要的朋友可以參考下2023-04-04