java - 带有 Socket 的 BufferedReader 未收到任何内容

标签 java android

我正在尝试在我的电脑上使用 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>

基于:Server socket program not executing after connection establishment 希望你能帮助我,Uku3lig

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

最佳答案

改变

        output.write("yeet");

        output.write("yeet\n");

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

关于java - 带有 Socket 的 BufferedReader 未收到任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60195979/

相关文章:

android - Alarmmanager 第一次触发但不会重复

java - Android 无法实例化一个或多个类

java - 如何修复 setProperty 中的奇怪顺序或放置 Properties 类

java - 如何获得通过电话接入点连接的设备数量?

android - 如何让用户从两个不同的 Intent 中进行选择?

android - 如何在 Eclipse 调试器中查看崩溃原因

android - runOnUiThread(new Runnable(){}) 对于 new Thread(){} 类型未定义

java - 如何找到文本中复合词的出现

java - TestScheduler 不适用于 RxJava

android - 在 Android 中使用录音的 SpeechRecognizer