服务器不向客户端发送消息(ESP8266)

时间:2017-03-18 18:32:05

标签: java sockets arduino esp8266 arduino-esp8266

我有一个问题,我不知道如何解决它。我正在尝试从服务器向客户端发送消息,但它不起作用,我甚至不知道为什么。 这是Java套接字服务器代码:

/*
 * 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");
}

1 个答案:

答案 0 :(得分:0)

在同一个应用程序中执行套接字通信客户端 - >服务器至少涉及两个线程。一个线程是服务器,一个是客户端。服务器线程使用server.accept()等待客户端连接。客户端线程基本上打开一个Socket,写一条消息并等待回答。

两个线程都需要一个Socket实例来读写通信。您的代码从两侧使用相同的实例。我想这个构造在你第一次点击按钮后会抛出一个NullPointerException。

客户端线程 - 这里是ButtonAction - 必须创建一个自己的Socket实例:

new Socket( "localhost", 8842).