【问题标题】:Sending text over wifi using sockets causes app to crash使用套接字通过 wifi 发送文本会导致应用程序崩溃
【发布时间】:2017-08-26 15:35:05
【问题描述】:

我正在尝试通过 wifi 从我的手机向我的电脑发送一条短信,但我的应用程序不断崩溃,我不知道为什么。这是崩溃的代码:

try {
 Socket socket = new Socket(RecieverIP,1755);
 DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
 DOS.writeUTF(String.valueOf(progressvalue));
 socket.close();
 } catch (IOException e) 
{
  e.printStackTrace();
 }    

在我的电脑端:

 import java.io.BufferedInputStream;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    /**
     *
     * @author fares Part of a project to control the led brightness on a pi, the job of this program is to receive a text over wifi and then launch a python program and pass the brightness as a parameter
     */
    public class WebSocketReciever {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException {

            System.out.println("Program started");
            String msg_received;
            System.out.println("Creating socket");
            ServerSocket socket = new ServerSocket(1755);
            System.out.println("Socket created");
            Socket clientSocket = socket.accept();       //This is blocking. It will wait.
            System.out.println("Client socket created");

            while(true){
            System.out.println("Reading data");
            DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
            msg_received = DIS.readUTF();
            System.out.println(msg_received);

            clientSocket.close();
            socket.close();}

        }
    }

如果我运行 pc 代码,它总是只能到达输出:“Socket created”

应用程序的整个代码是:

package com.example.fares.ledslider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import static com.example.fares.ledslider.R.id.seekBar;

public class MainActivity extends AppCompatActivity {

    private static TextView textView;
    private static SeekBar seek_Bar;
    private static String RecieverIP;
    private static EditText IPText;

    public void seekbarmethod(){
        seek_Bar = (SeekBar) findViewById(seekBar);
        textView = (TextView) findViewById(R.id.textview);
        seek_Bar.setMax(100); //Max value of the seekbar
        seek_Bar.setProgress(50);//Initial seekbar value
        textView.setText("Brightness = " +seek_Bar.getProgress() + " %"); //Notify user of percentage brightness
        seek_Bar.setOnSeekBarChangeListener(
                new SeekBar.OnSeekBarChangeListener(){
                    int count =0;
                    int progressvalue;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                        progressvalue = i;
                        textView.setText("Brightness = " + progressvalue + " %");

                          //  Toast.makeText(MainActivity.this,"Change in progress" + count,Toast.LENGTH_SHORT).show();
                            //count +=1;
                        //Send data from app to pc

                        try {
                           Socket socket = new Socket(RecieverIP,1755);
                            DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());

                            DOS.writeUTF(String.valueOf(progressvalue));
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }



                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                        Toast.makeText(MainActivity.this,"Change initiated",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        Toast.makeText(MainActivity.this,"Change ended",Toast.LENGTH_SHORT).show();
                        count = 0 ;

                    }
                }
        );

    }

    public void IPBtnMethod(View v){
    IPText = (EditText) findViewById(R.id.IPBox);
    RecieverIP = IPText.getText().toString();
    Toast.makeText(MainActivity.this,"IP = " + RecieverIP,Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekbarmethod();

    }
}

为什么我的应用会崩溃,我该如何解决?提前致谢

【问题讨论】:

  • 在 Android 中,您不是在主线程上进行网络连接。看到这个:stackoverflow.com/questions/6343166/…
  • @ErvinSzilagyi 好的,谢谢,你知道这是为什么吗?
  • 这是 Android 团队的设计决定。可能不会通过锁定你的主线程来冻结你的应用程序。
  • 再次感谢,如果您想回答而不是发表评论,那么我可以投票给您正确的投票,那就太好了
  • 我也写了一个答案。

标签: java android sockets


【解决方案1】:

您可能会收到NetworkOnMainThreadException 异常。当您在主线程上进行联网时会引发此异常。 Android 操作系统禁止这样做:https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多