我必須允許客戶端爲我的項目執行查詢,但我不知道如何將我的客戶端/服務器應用程序連接到MySQL。我只知道如何在單獨的類中連接到MySQL。有什麼建議麼?將MySQL連接到Java客戶端/服務器應用程序
服務器:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
private int port;
public Server(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for clients. Block till one connects
System.out.println("Waiting for clients...");
Socket client = serverSocket.accept();
//A client has connected to this server. Send welcome message
sendWelcomeMessage(client);
}
private void sendWelcomeMessage(Socket client) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("Hello. You are connected to Server. What is your name?");
writer.flush();
}
/**
* Creates a SocketServer object and starts the server.
*
* @param args
*/
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 1234;
try {
// initializing the Socket Server
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port){
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Attempting to connect to "+hostname+":"+port);
socketClient = new Socket(hostname,port);
System.out.println("Connection Established");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
Client client = new Client ("localhost",1234);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
}
}
}
我在這裏沒有看到與「MySQL」的連接。這是一些客戶端 - 服務器通信應用程序存根... – mareckmareck
你能詳細說明這個MySQL連接在代碼中的位置嗎?客戶端或服務器端? –
你甚至嘗試過嗎? –