当前位置:网站首页>JDBC连接数据库,socket发送客户端。
JDBC连接数据库,socket发送客户端。
2022-06-29 06:37:00 【inspire121】
自己用Java写了个客户端通过服务器实时读取MySQL数据库的程序。JDBC实时读取数据库数据,并每隔1秒发送给客户端,客户端处于一直接收状态,测试用IP:127.0.0.1,端口号为7000。先运行服务器,再运行客户端。源程序如下:
服务端:
在这里插入代码片
package server;
import java.io.*;
import java.net.*;
import java.sql.*;
public class Server{
public static void main(String args[]){
while(true) {
//socket
ServerSocket server=null;
Socket you=null;
try {
server =new ServerSocket(7000);
}
catch (IOException el) {
System.out.println("正在监听");
}
try {
System.out.println("等待客户呼叫");
you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch(IOException e) {
System.out.println("正在等待客户");
}
if(you!=null) {
ServerThread threadForClient=new ServerThread(you);
threadForClient.start();
}
}
}
}
class ServerThread extends Thread{
static int id;
static int name;
static int password;
static int email;
static int birthday;
Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
ServerThread(Socket t){
socket=t;
try {
out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
} catch (IOException e) {
}
}
public void run() {
//JDBC初始化
// JDBC 驱动名及数据库 URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/data?useSSL=true";
// 数据库的用户名与密码,需要根据自己的设置
final String USER = "root";
final String PASS = "root";
//jdbc
Connection conn = null;
Statement stmt = null;
while(true) {
try {
double r=in.readDouble();
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id,name,password,email,birthday FROM data";
ResultSet rs = stmt.executeQuery(sql);
if(rs.last()){
//只读取最后一个ID
// 通过字段检索
id = rs.getInt("id");
name = rs.getInt("name");
password = rs.getInt("password");
email = rs.getInt("email");
birthday = rs.getInt("birthday");
}
out.writeDouble(ServerThread.id);
out.writeDouble(ServerThread.name);
out.writeDouble(ServerThread.password);
out.writeDouble(ServerThread.email);
out.writeDouble(ServerThread.birthday);
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}
try{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
客户端:
在这里插入代码片
package server;
import java.io.*;
import java.net.*;
import java.util.*;
public class Client{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
Socket mysocket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread readData;
Read read=null;
try {
mysocket=new Socket();
read=new Read();
readData=new Thread(read);
System.out.print("输入服务器的IP:");
String IP=scanner.nextLine();
System.out.print("输入端口号:");
int port=scanner.nextInt();
InetAddress address = InetAddress.getByName(IP);
InetSocketAddress socketAddress = new InetSocketAddress(address, port);
mysocket.connect(socketAddress);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
read.setDataInputStream(in);
readData.start();
}
catch(Exception e) {
System.out.println("服务器已断开"+e);
}
System.out.println("接收数据:");
while(true) {
double radius=0;
try {
out.writeDouble(radius);
}
catch (Exception e) {
}
}
}
}
class Read implements Runnable{
DataInputStream in;
public void setDataInputStream(DataInputStream in) {
this.in=in;
}
public void run() {
double id=0;
double name=0;
double password=0;
double email=0;
double birthday=0;
while (true) {
try {
id=in.readDouble();
System.out.println("id:"+id);
name=in.readDouble();
System.out.println("名字:"+name);
password=in.readDouble();
System.out.println("密码:"+password);
email=in.readDouble();
System.out.println("邮箱:"+email);
birthday=in.readDouble();
System.out.println("生日:"+birthday);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
MySQL数据如下(只有数字),每隔1秒读取最后一行数据:
边栏推荐
- The simple problem of leetcode is to divide an array into three parts equal to sum
- Presto-Trial
- String and variable are spliced into variable name
- P5 DS - component and document Association
- VerilogA——计数器
- Fresnel diffraction with rectangular aperture based on MATLAB
- Failure: unable to log in to "taxpayer equity platform"
- Chapter V online logic analyzer signaltap
- Ribbon service invocation and load balancing
- It is the only one in China that Alibaba cloud container service has entered the Forrester leader quadrant
猜你喜欢

Baidu applet automatically submits search

There are two ways for golang to develop mobile applications

Pointer from beginner to advanced (2)

Agile invincible event

解析学习幼儿机器人教育的浪潮
![[C language] flexible array](/img/22/3255740602232abfdf69624762adca.jpg)
[C language] flexible array

关于DDNS

Sum of digits under k-ary representation of leetcode simple problem

Pytest (7) -yield and termination function

Easy to understand TCP four waves (multi picture explanation)
随机推荐
Character pointer as function parameter
Honeypot based on MySQL load data local INFILE
Can I cast int to a variable of type byte? What happens if the value is larger than the range of byte type?
Difference between static and final
Analytic hierarchy process
Share 10 interview questions related to JS promise
How to change the password after forgetting the MySQL password (the latest version of 2022 detailed tutorial nanny level)
Illustrate plug-in -- AI plug-in development -- creative plug-in -- astute graphics -- length and angle measurement function
[Flink] flinksql and table programming cases
Hyperledger Fabric 2. X custom smart contract
Pytest (7) -yield and termination function
Object detection - VIDEO reasoning using yolov6
Linux Installation redis
Two houses with different colors and the farthest distance
Servlet version conflict causes page 404
Hyperledger Fabric 2. X custom smart contract
What are the uses of final?
Pointer from beginner to advanced (2)
What are the uses of wireless pressure collectors?
Baidu applet automatically submits search