所以基本上,我想做的是通过我创建的服务器从我的数据库 MySQL 中读取数据。我将数据库中的信息放在一个 ArrayList 中,但客户端无法读取它。当我添加简单的字符串时,它可以工作。但不是当它来自我的数据库时。有什么解决办法吗?
public class Server implements Runnable {
private ServerSocket server;
private Socket socket;
private ObjectOutputStream oos = null;
public Server() {
try {
server = new ServerSocket(4444);
new Thread(this).start();
} catch (Exception e) {
System.out.println(e);
}
}
public void run() {
System.out.println("Server running");
while (true) {
try {
socket = server.accept();
sayHi();
System.out.println("Hallå");
} catch (Exception e) {
}
}
}
private void sayHi(){
DataOutputStream dos;
try {
dos = new DataOutputStream(socket.getOutputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
dos.writeUTF("Hej");
sendNames();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendNames() {
ArrayList<String> drinkar = new ArrayList<String>();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "drycker";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = (Statement) con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM drinktable");
while (res.next()) {
String s = res.getString("Name");
for(int i = 0; i<drinkar.size(); i++){
drinkar.add(s);
}
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
ArrayList<String> a = new ArrayList<String>();
a.add("Hejsan");
a.add("Svejsan");
try {
FileOutputStream fos = new FileOutputStream("randomList");
oos = new ObjectOutputStream(fos);
oos.writeObject(drinkar);
oos.flush();
oos.reset();
oos.close();
fos.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
public class Client implements Runnable {
private Socket socket;
private DataInputStream dis;
private ObjectInputStream ois = null;
public Client() {
socket = new Socket();
InetSocketAddress ipPort = new InetSocketAddress("192.168.0.10", 4444);
try {
socket.connect(ipPort);
dis = new DataInputStream(socket.getInputStream());
ois = new ObjectInputStream(socket.getInputStream());
} catch (Exception e) {
}
new Thread(this).start();
}
public void run() {
while (true) {
try {
String msg = dis.readUTF();
if (msg.equals("Hej")) {
Thread.sleep(50);
receiveArrayList();
}
} catch (Exception e) {
}
}
}
public void receiveArrayList() {
try {
FileInputStream fis = new FileInputStream("randomList");
ois = new ObjectInputStream(fis);
ArrayList<String> a= (ArrayList<String>) (ois.readObject());
for(int i = 0; i < a.size(); i++){
System.out.println((String)a.get(i));
}
ois.close();
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
new Client();
}
}