2017-03-18 167 views
-2

我有一個問題,我不知道如何解決它。我試圖從服務器發送消息給客戶端,但它不起作用,我甚至不知道爲什麼。 這裏是Java套接字服務器代碼:服務器不發送消息給客戶端(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     
} 

這裏是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"); 
} 

回答

0

做同樣的應用程序內套接字通信客戶端 - >服務器以最小涉及兩個線程。一個線程是服務器,一個是客戶端。服務器線程用server.accept()等待客戶端連接。客戶端線程基本上打開一個Socket,寫一條消息並等待回答。

兩個線程都需要一個Socket實例來讀取和寫入通信。您的代碼使用來自兩側的相同實例。我想這個構造在第一次點擊按鈕後會拋出一個NullPointerException異常。

客戶端線程 - 這裏的ButtonAction - 必須創建自己的Socket實例:

new Socket("localhost", 8842). 
相關問題