i have a server that work if change String with clients. Now,i want to use Object instead of String but the server doesn't receive anything and get stugged before the sout like the client doesn't sand anything...So, the problem is on the client or on the server?? Message is a class with interface Serializable and i called input before output in server and output before input in client.
Server:
public class ControllerServer {
@FXML
public ListView<Log> log_list;
@FXML
public MenuItem disconnect_button;
@FXML
public MenuItem connect_button;
boolean connection = true;
DataModel model;
ObservableList<Log> list;
Connection conn = new Connection();
@FXML
public void initialize() throws TransformerConfigurationException {
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
model = new DataModel();
list = model.getLogList();
log_list.setItems(list);
log_list.getSelectionModel().selectedItemProperty().addListener((obs,oldLog,newLog) -> model.setCurrentLog(newLog));
model.currentEmailProperty().addListener((obs, oldLog, newLog) -> {
if (newLog == null) {
log_list.getSelectionModel().clearSelection();
} else {
log_list.getSelectionModel().select(newLog);
}
});
log_list.setCellFactory(lv -> new ListCell<Log>() {
@Override
public void updateItem(Log message, boolean empty) {
super.updateItem(message, empty);
if (empty) {
setText(null);
} else {
setText(message.getContent());
}
}
});
conn.start();
}
public void disconnect(ActionEvent actionEvent) {
if(connection){
connection = false;
conn.cancel();
if(disconnect_button!=null)disconnect_button.setVisible(false);
if(connect_button!=null)connect_button.setVisible(true);
}else System.out.println("The server is closed!");
}
public void connect(ActionEvent actionEvent) {
if(!connection){
conn.restart();
connection = true;
if(disconnect_button!=null)disconnect_button.setVisible(true);
if(connect_button!=null)connect_button.setVisible(false);
}
else System.out.println("Already connected");
}
public class Connection extends Service<Void>{
ServerSocket s;
ExecutorService listeners = Executors.newCachedThreadPool();
ArrayList<Socket> incomings_connection = new ArrayList<>();
int id=1;
@Override
protected Task<Void> createTask() {
return new Task<>() {
@Override
protected Void call() {
System.out.println("Server Attivo");
try {
s = new ServerSocket(8189);
while (!isCancelled()) {
Thread.sleep(500);
System.out.println("In attesa di connessione....");
Socket incoming = s.accept();
incomings_connection.add(incoming);
Task<Void> listener = new Task<Void>() {
@Override
protected Void call() throws Exception {
int id_task = id;
System.out.println("Connessione accettata! Client: "+id_task);
ObjectInputStream inStream = new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream outStream = new ObjectOutputStream(incoming.getOutputStream());
Message request;
while (!isCancelled()){
Object obj = inStream.readObject();
try{
request = (Message)obj;
System.out.println("Arrivato: "+request.getMessage()+" e: "+request.getAction());
}catch (ClassCastException e){
e.printStackTrace();
}
}
return null;
}
};
listeners.submit(listener);
id++;
}
}catch (SocketException ex){
System.out.println("Listener chiuso!");
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void cancelled() {
System.out.println("Closing server....");
System.out.println("Done!");
try {
s.close();
try {
System.out.println("Connessioni chiuse: "+incomings_connection.size());
for(Socket conn: incomings_connection){
conn.close();
}
}catch (NullPointerException EX){
System.out.println("Non è stata stabilita nessuna connesione client prima della chiusura!");
}
model.closeLog();
}
catch (NullPointerException EX){
System.out.println("Server non inizializzato correttamente");
}
catch (IOException e) {
e.printStackTrace();
}
super.cancelled();
}
};
}
private String login(String email) {
String response = null;
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Huawei\\OneDrive\\Desktop\\Università\\prog3\\Progetto\\Server\\src\\main\\resources\\Utenti\\"+email+"\\Info.txt"));
response = reader.readLine();
} catch (FileNotFoundException e) {
response = "Error: user inesistente";
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
}
Client
public class ControllerClient {
Log log = new Log();
Connection conn;
@FXML
public TextField email;
@FXML
public Button submit_button;
@FXML
public Label ConnectionFailureText;
@FXML
public Button try_connect;
@FXML
public void initialize() {
connect();
}
private void connect() {
conn = new Connection(log);
conn.start();
}
public void re_connect(ActionEvent event){
}
public void login(ActionEvent actionEvent) {
if(this.conn.isRunning()){
if (email.getText()!=null && email.getText()!="" ){
log.put(new Message("login",email.getText()));
}else System.out.println("Inserisci la mail!");
}
else System.out.println("Connessione chiusa!");
}
class Connection extends Service<Void> {
Log log;Socket s;
public Connection(Log item){
log = item;
}
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
try {
String nomeHost = InetAddress.getLocalHost().getHostName();
s = new Socket(nomeHost, 8189);
System.out.println("Ho aperto il socket verso il server");
try{
ObjectOutputStream outStream = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream inStream = new ObjectInputStream(s.getInputStream());
System.out.println("Sto per ricevere dati dal socket server!");
Message message = null;
while (!isCancelled()) {
message = log.get();
if(message!=null){
System.out.println("message: "+message.getMessage() + " " +message.getAction());
outStream.writeObject(message);
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("Connessione col server interrotta!");
s.close();conn.cancel();
}
}catch (Exception e){
e.printStackTrace();
System.out.println("Errore di connessione!");
}
return null;
}
};
}
@Override
protected void cancelled() {
System.out.println("Connessione chiusa");
super.cancelled();
}
}
}
class Log {
private boolean available = false;
private Message message = null;
public synchronized Message get(){
while (!available) {
try {
wait();
} catch (InterruptedException e) {
}
}
/* fondamentale notifyAll(), anziché notify(), per prevenire deadlock */
available = false;
notifyAll();
return message;
}
public synchronized void put(Message value) {
while (available) {
try {
wait();
} catch (InterruptedException e) { }
}
message = value;
available = true;
notifyAll();
}
}
Message:
public class Message implements Serializable {
private String action;
private String message;
private Email email;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
public Message(String action, String message){
this.action=action;
this.message=message;
}
public Message(String action, String message, Email email){
this.action=action;
this.message=message;
this.email = email;
}
}
flush()afterwriteObject. And consider always closing resources after use, not only in the exceptional case.flush()afterwriteObject" means that the code callingwriteObjectshould do that, right afterwards. That's the client in the code you've posted.flush()?