【问题标题】:BufferedReader with Socket not receiving anything [duplicate]带有Socket的BufferedReader没有收到任何东西[重复]
【发布时间】:2020-02-12 19:57:55
【问题描述】:

我正在尝试为我的电脑做一个遥控器,在我的电脑上使用一个 android 应用程序和一个 java 程序。 我在端口 8000 上使用了一个套接字,它可以毫无问题地连接,但是在读取从我的 android 手机发送的消息时,它什么也没做。这是代码: pc/Main.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;

import static java.lang.Thread.sleep;

public class Main {
    private static String SERVER_IP;
    private static final int SERVER_PORT = 8000;
    private static HashSet<String> addr = new HashSet<>(Collections.emptySet());
    public static void main(String[] args) {
        if (args[0].equals("fast")) {
            addr.add("192.168.1.13");
        } else {
            for (int i = 1; i < 256; i++) {
                System.out.print(((i % 4) == 0 ? (i / 4 % 5 == 0 ? i / 4 + "%\n" : "") : ""));
                SERVER_IP = "192.168.1." + i;
                Socket socket = new Socket();
                boolean b = false;
                try {
                    socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), 200);
                    socket.close();
                    if (!SERVER_IP.equals("192.168.1.100")) addr.add(SERVER_IP);
                    b = true;
                } catch (IOException ignored) {
                }
                if (b) {
                    System.out.println("\u001B[32m" + SERVER_IP + " is on the network !" + "\u001B[0m");
                }
            }
        }
        new Thread(new Init()).start();
    }

    private static BufferedReader input;
    static class Init implements Runnable {
        Socket socket;
        @Override
        public void run() {
            addr.forEach(addr -> {
                try {
                    socket = new Socket(addr, SERVER_PORT);
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("connected hehe to " + addr);
                    new Thread(new MessageReader()).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
    static class MessageReader implements Runnable {
        @Override
        public void run() {
                while (true) {
                    System.out.println("aaaa");
                    try {
                        String msg;
                        System.out.println(msg = input.readLine());
                        System.out.println("ive read the line yeet");
                        if (msg != null) {
                            System.out.println(msg);
                        } else {
                            new Thread(new Init()).start();
                            return;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        }
    }
}

android/Main.java

package net.uku3lig.gameapi;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class Main extends AppCompatActivity {
    public static String ip = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = findViewById(R.id.button);
        TextView t = findViewById(R.id.textView);
        //get ip
        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        assert wm != null;
        try {
            ip = InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)
                    .putInt(wm.getConnectionInfo().getIpAddress()).array()).getHostAddress();
        } catch (UnknownHostException e) { e.printStackTrace(); }
        assert ip != null;
        t.setText(ip);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    new Thread(new Sender(Arrays.asList("ah","shit","here","we","go","again").get((int) Math.round(Math.random()*5)))).start();
            }
        });
    }


    private PrintWriter output;
    class Sender implements Runnable {
        private String msg;
        Sender(String msg) {
            this.msg = msg;
        }
        @Override
        public void run() {
            Socket socket;
            ServerSocket ss;
            try {
                ss = new ServerSocket(8000);
                ss.setReuseAddress(true);
                socket = ss.accept();
                output = new PrintWriter(socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.write("yeet");
            output.flush();
        }
    }
}

android/main.xml(应用布局)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Main">

    <Button
            android:text="lick me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="340dp" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginLeft="160dp" android:layout_marginStart="160dp"
    />
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="388dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="160dp"
            android:layout_marginStart="160dp"/>
    <TextView
            android:text="TextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView" android:layout_marginBottom="24dp"
            app:layout_constraintBottom_toTopOf="@+id/button2" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginLeft="175dp" android:layout_marginStart="175dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

android/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.uku3lig.gameapi">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

基于:https://www.tutorialspoint.com/how-to-send-data-through-wifi-in-android-programmatically 希望你能帮助我,Uku3lig

PS:执行软件的部分不见了,这很正常,我暂时只关注数据发送部分。

【问题讨论】:

  • 您正在阅读线路,但您没有发送线路。将 write() 更改为 println()。但是这段代码还有很多其他问题。 input 例如不应该是静态的,并且其他几个变量的范围错误。打开一个套接字然后立即关闭它是在浪费时间和两端安抚,
  • 如果连接/关闭失败,以及readLine() 返回 null 时,您也会泄漏套接字。

标签: java android


【解决方案1】:

改变

        output.write("yeet");

        output.write("yeet\n");

这应该可行。问题是 BufferedReader.readLine() 被阻塞等待换行符

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多