2017-03-18 2 views
-2

J'ai un problème que je n'ai aucune idée de comment le résoudre. J'essaye d'envoyer un message du serveur au client mais cela ne fonctionne pas et je ne sais même pas pourquoi. Voici le code du serveur socket Java:Le serveur n'envoie pas de message au client (ESP8266)

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package homeautomation; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 

/** 
* 
* @author WisterDeisgns 
*/ 
public class GUI_TCPServer extends javax.swing.JFrame { 

    /** 
    * Creates new form GUI_TCPServer 
    */ 
    //TCP server Code. 
    static ServerSocket server; 
    static Socket client; 
    static BufferedReader in; 
    static BufferedWriter out; 
    static String ServerPort = ""; 

    public GUI_TCPServer() { 
     initComponents(); 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code">       
    private void initComponents() { 

     jScrollPane1 = new javax.swing.JScrollPane(); 
     ConsoleBox = new javax.swing.JTextArea(); 
     jLabel1 = new javax.swing.JLabel(); 
     MessageField = new javax.swing.JTextField(); 
     SendButton = new javax.swing.JButton(); 
     jLabel3 = new javax.swing.JLabel(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     ConsoleBox.setColumns(20); 
     ConsoleBox.setRows(5); 
     jScrollPane1.setViewportView(ConsoleBox); 

     jLabel1.setText("Console"); 

     SendButton.setText("Send"); 
     SendButton.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       SendButtonActionPerformed(evt); 
      } 
     }); 

     jLabel3.setText("Message"); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addComponent(jLabel1) 
        .addComponent(jLabel3) 
        .addGroup(layout.createSequentialGroup() 
         .addComponent(MessageField, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addGap(18, 18, 18) 
         .addComponent(SendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))) 
       .addContainerGap(19, Short.MAX_VALUE)) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addGap(13, 13, 13) 
       .addComponent(jLabel1) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(jLabel3) 
       .addGap(2, 2, 2) 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(MessageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addComponent(SendButton)) 
       .addContainerGap(106, Short.MAX_VALUE)) 
     ); 

     pack(); 
    }// </editor-fold>       

    private void SendButtonActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
     try{ 

      String msgout = ""; 
      msgout = MessageField.getText().trim(); 
      out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); 
      out.write(msgout , 0 , msgout.length()); 
      out.flush(); 
      out.close(); 
      //dout.writeUTF(msgout); //Sending server message to client... 

     }catch(Exception e){ 
      //Handle the exception here... 
     } 
    }           

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) throws IOException { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(GUI_TCPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(GUI_TCPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(GUI_TCPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(GUI_TCPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new GUI_TCPServer().setVisible(true); 
      } 
     }); 

     String msgin = ""; 

     try{ 

      server = new ServerSocket(8442); //server starts at 8442 port number 
      //if(client == null) 
       //ConsoleBox.setText(ConsoleBox.getText().trim() + "\n" + "Server > client is null!"); 
      client = server.accept(); //Server accepts the connections 

      //din = new DataInputStream(client.getInputStream()); 
      //dout = new DataOutputStream(client.getOutputStream()); 
      ConsoleBox.setText(ConsoleBox.getText().trim() + "\n" + "Server > Has successfully started!"); 
      ConsoleBox.setText(ConsoleBox.getText().trim() + "\n" + "Server > Port: 8442"); 
      ConsoleBox.setText(ConsoleBox.getText().trim() + "\n" + "Server > Client connected, " + client.getInetAddress()); 

      in = new BufferedReader(new InputStreamReader(client.getInputStream())); 

      //InputStream is = client.getInputStream(); 
      //InputStreamReader isr = new InputStreamReader(is); 
      //BufferedReader br = new BufferedReader(isr); 
      //String inputText = br.readLine(); 

      msgin = in.readLine(); 
      //msgin = din.readUTF(); 
      ConsoleBox.setText(ConsoleBox.getText().trim() + "\n" + msgin); //displaying the incomming message... - from client 

      //din.close(); 

     }catch(Exception e){ 

     } 
    } 

    // Variables declaration - do not modify      
    private static javax.swing.JTextArea ConsoleBox; 
    private javax.swing.JTextField MessageField; 
    private javax.swing.JButton SendButton; 
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JLabel jLabel3; 
    private javax.swing.JScrollPane jScrollPane1; 
    // End of variables declaration     
} 

Voici le code ESP8266:

#include <ESP8266WiFi.h> 
#include <WiFiClient.h> 

const char* ssid = "HotBox"; 
const char* pass = ""; 
const char* host = "192.168.1.112"; 

void setup() { 
    delay(500); 
    Serial.begin(115200); 
    Serial.println(); 
    Serial.print("conecting to: "); 
    Serial.println(ssid); 
    Serial.println("Try to connect to server: "); 
    Serial.println(host); 

    WiFi.mode(WIFI_STA); 
    delay(1000); 
    WiFi.begin(ssid, pass); 
    //IPAddress subnet(255,255,255,0); 
    //WiFi.config(IPAddress(192,168,1,150),IPAddress(192,168,1,10),subnet); 

    while (WiFi.status() != WL_CONNECTED) { 
    delay(1000); 
    Serial.print("."); 
    } 

    Serial.println(); 
    Serial.print("My IP: "); 
    Serial.println(WiFi.localIP()); 
    long rssi = WiFi.RSSI(); 
    Serial.print("RSSI: "); 
    Serial.print(rssi); 
    Serial.println(" dBm"); 
} 

void loop() { 

    WiFiClient client; 

    if (!client.connect(host,8442)) { //The problem start here 
    Serial.println("."); 
    return; 
    } 

    //Serial.println(); 
    //Serial.print("Conected to IP: "); 
    //Serial.println(host); 

    //Serial.println("Sending string to server: "); 
    client.println("OK"); 

    String line = client.readStringUntil('\n'); 
    if(line != "") 
    Serial.println("Server > Data string: " + line); 

    //Serial.println(); 
    //Serial.println("Closing connection"); 
    client.flush(); 
    client.stop(); 
    //Serial.println("Connection Closed"); 
} 

Répondre

0

Faire client- communication socket> serveur au sein de la même application implique deux fils au minimum. Un thread est le serveur, un le client. Le thread de serveur attend avec server.accept() pour une connexion client. Le thread client ouvre essentiellement un socket, écrit un message et attend une réponse.

Les deux threads ont besoin d'une instance Socket pour lire et écrire la communication. Votre code utilise la même instance des deux côtés. Je suppose que cette construction jette une exception NullPointerException après votre premier clic sur le bouton.

Le thread client - ici le ButtonAction - doit créer une propre instance de Socket:

new Socket("localhost", 8842).