我有以下tcp服务器:
public class Server {
private Connection db;
private Statement statement;
private ServerSocket socket;
public static void main(String[] args) {
Server server = new Server();
server.initializeServer();
System.out.println("Server initialized");
server.listenConnections();
}
private void initializeServer() {
try {
db = DriverManager.getconnection("jdbc:mysql://localhost:3306/courseworkschema" +
"?verifyServerCertificate=false" +
"&useSSL=false" +
"&requireSSL=false" +
"&useLegacyDatetimeCode=false" +
"&" +
"&serverTimezone=UTC","Sergei","12345");
statement = db.createStatement();
socket = new ServerSocket(1024);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
private void listenConnections() {
System.out.println("Listening connections ... ");
while (true) {
try {
Socket client = socket.accept();
new Thread(() -> {
System.out.println("Client accepted");
try {
OutputStream outputStream = client.getOutputStream();
InputStream inputStream = client.getInputStream();
String clientaction;
String queryContent;
boolean flag = true;
while (flag) {
byte[] msg = new byte[100];
int k = inputStream.read(msg);
clientaction = new String(msg,k);
clientaction = clientaction.trim();
msg = new byte[100];
k = inputStream.read(msg);
queryContent = new String(msg,k);
queryContent = queryContent.trim();
System.out.println(clientaction);
System.out.println(queryContent);
if (clientaction.equalsIgnoreCase("END")) {
flag = false;
}
else if (clientaction.equalsIgnoreCase("LOGIN")) {
System.out.println("Login action");
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
已创建此服务器以与数据库通信。这是我尝试连接到此服务器的方式L
public class LoginController {
private LoginWindow window;
private Socket socket;
private InputStream is;
private OutputStream os;
public LoginController() {
connectToServer();
}
public void logInUser(String login,String password) {
if (!login.isEmpty() && !password.isEmpty()) {
sendDataToServer("LOGIN");
sendDataToServer("");
} else {
window.showmessagedialog("Fill the fields!",JOptionPane.ERROR_MESSAGE);
}
}
public void attachView(LoginWindow window) {
this.window = window;
}
private void connectToServer() {
try {
socket = new Socket("127.0.0.1",1024);
System.out.println("Connected");
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendDataToServer(String res) {
try {
os = socket.getOutputStream();
os.write(res.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行服务器然后运行客户端时,我在服务器中有这样的日志:
Server initialized
Listening connections ...
Process finished with exit code -1
所以,我不明白为什么服务器不等待并接受来自客户端的连接,而是在初始化和侦听后关闭。那怎么了我将不胜感激。预先感谢!
UPD
当我运行我的应用程序时,它开始工作,但是我发现 Thread 块中的代码未执行。我什至不明白,为什么会发生