有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

socket未接收任何内容的java BufferedReader

我正在尝试为我的电脑做一个遥控器,在我的电脑上使用安卓应用程序和java程序。 我在端口8000上使用了一个socket,它连接起来没有问题,但是当我阅读安卓手机发送的信息时,它什么都不做。代码如下: pc/Main。爪哇

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();
                    }
                }
        }
    }
}

安卓/Main。爪哇

package net.uku3lig.gameapi;

import 安卓.net.wifi.WifiManager;
import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.TextView;
import 安卓x.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();
        }
    }
}

安卓/main。xml(应用程序布局)

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

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

安卓/AndroidManifest。xml

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

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

</manifest>

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

PS:执行软件的部分缺失,这是正常的,我现在只关注数据发送部分


共 (1) 个答案

  1. # 1 楼答案

    改变

            output.write("yeet");
    

            output.write("yeet\n");
    

    这应该行得通。问题是BufferedReader。readLine()在等待换行符时被阻止