如何将数据从手机发送到服务器?

时间:2019-02-28 17:12:06

标签: java android server

我正在尝试使用套接字将数据从手机(客户端)发送到服务器。 我的代码在模拟器中运行,但在手机中不起作用。在仿真器中,它可以将数据发送到在NetBeans中创建的服务器。 我曾尝试将手机和笔记本电脑连接到同一热点,但是仍然无法正常工作。 我的Android代码是:

package dead.server;

import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText editText;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=findViewById(R.id.editText);
        button=findViewById(R.id.button);

        button.setOnClickListener(this);

        Thread mythread=new Thread(new ThreadServer());
        mythread.start();

    }

    @Override
    public void onClick(View view) {
        String message=editText.getText().toString();
        new Backgound().execute(message);
        Toast.makeText(this, "Sent", Toast.LENGTH_SHORT).show();
    }

    //Sending Data to server

    class Backgound extends AsyncTask<String,Void,Void>{

        Socket s;
        PrintWriter printWriter;
        @Override
        protected Void doInBackground(String... strings) {
            try {
                s=new Socket("192.168.43.166",5000);
                Log.d("Server","Sent");
                printWriter=new PrintWriter(s.getOutputStream());
                printWriter.write(strings[0]);
                printWriter.flush();
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

        }
    }

  //  Reciving Data from Server
    class ThreadServer implements Runnable{

        Socket s;
        ServerSocket ss;
        BufferedReader bf;
        String message;
        Handler handler=new Handler();

        @Override
        public void run() {
            try {
                ss = new ServerSocket(5000);

                while (true){
                    s=ss.accept();
                    bf=new BufferedReader(new InputStreamReader(s.getInputStream()));
                    message=bf.readLine();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);

                        }
                    });

                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}

NetBeans IDE代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * 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.
 */

/**
 *
 * @author hp
 */
public class MyServerFrame extends javax.swing.JFrame {
        static Socket s;
        static ServerSocket ss;
        static BufferedReader bf;
        static String message;
    /**
     * Creates new form MyServerFrame
     */
    public MyServerFrame() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(87, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(79, 79, 79)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(101, Short.MAX_VALUE))
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* 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(MyServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyServerFrame.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 MyServerFrame().setVisible(true);
            }
        });
        try {
                ss = new ServerSocket(5000);

                while (true){
                    s=ss.accept();
                    bf=new BufferedReader(new InputStreamReader(s.getInputStream()));
                    message=bf.readLine();
                    System.out.println(message);
                    jTextArea1.setText(message);


                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   
}

0 个答案:

没有答案