亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 TCP 套接字發送消息 - Java

通過 TCP 套接字發送消息 - Java

qq_花開花謝_0 2022-08-17 17:00:19
我試圖在Android中通過TCP套接字發送消息,但它不起作用。(我的手機是客戶端)下面是來自類 TCPClient 的代碼:public class TcpClient {    public static String SERVER_IP = "192.168.200.1"; //server IP address    public static final int SERVER_PORT = 1500;    // message to send to the server    private String mServerMessage;    // sends message received notifications    private OnMessageReceived mMessageListener = null;    // while this is true, the server will continue running    private boolean mRun = false;    // used to send messages    private PrintWriter mBufferOut;    // used to read messages from the server    private BufferedReader mBufferIn;    private Socket socket;    private Context context;    /**     * Constructor of the class. OnMessagedReceived listens for the messages received from server     */    public TcpClient(OnMessageReceived listener) {        mMessageListener = listener;    }    /**     * Sends the message entered by client to the server     *     * param message text entered by client     */    public String sendMessage(String message) {        byte[] bytesToSend = message.getBytes();        if (bytesToSend != null && socket != null && socket.isConnected()) {            try {                socket.getOutputStream().write(bytesToSend, 0, 9);                return "deu";            } catch (Exception e2) {                e2.printStackTrace();                return e2.getMessage();            }        }        else return "aa";    }    /**     * Close the connection and release the members     */    public void stopClient() {        sendMessage("disconnecting");        mRun = false;        if (mBufferOut != null) {            mBufferOut.flush();            mBufferOut.close();        }        mMessageListener = null;        mBufferIn = null;        mBufferOut = null;        mServerMessage = null;    }
查看完整描述

1 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

無需為你的英語感到抱歉!它完全沒:)


android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1598)

當您的應用程序嘗試在主線程上執行任何網絡操作時,將引發上述錯誤。


您可以使用下面的代碼強制操作或創建單獨的線程并執行操作。


備選案文1:強迫


    int SDK_INT = android.os.Build.VERSION.SDK_INT;

    if (SDK_INT > 8) 

    {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

                .permitAll().build();

        StrictMode.setThreadPolicy(policy);

        //your codes here


    }

選項 2:單獨的螺紋


Thread thread = new Thread(new Runnable() {

            @Override

            public void run() {

                // do something in here

            }

        });

thread.start();


查看完整回答
反對 回復 2022-08-17
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號