如何在android中用java作为后台创建一对一聊天?

gg0vcinb  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(197)

我正在尝试创建一个聊天应用程序。服务器是用java代码编写的,而客户端则是我试图用android编写的。当我在java中尝试服务器和客户机时,它工作得很好。但是,当我试图在android中创建一个客户端时,它不起作用。代码如下:
主要活动

package com.e.chatapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MainActivity extends AppCompatActivity {

    private TextView viewMsg;
    private EditText enterMsg;
    private Button sendMsg;
    private Socket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.initializeWidgets();
        this.createSocket();
    }

    private void initializeWidgets(){
        viewMsg = (TextView)findViewById(R.id.viewMsg);
        enterMsg = (EditText) findViewById(R.id.enterMsg);
        sendMsg = (Button) findViewById(R.id.sendMsg);
    }

    private void createSocket(){
        new Thread(this.handShake()).start();
    }

    private Runnable handShake() {
        Runnable handShake = () -> {
            try {
                socket = new Socket("127.0.0.1", 1234);
                this.startThreadsToSendAndReceiveMessages();
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
        return handShake;
    }

    private void startThreadsToSendAndReceiveMessages(){
        try {
            new Thread(sendMessageToClient()).start();
            new Thread(receiveMessageFromClient()).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Runnable sendMessageToClient() throws IOException {
        // sendMessage thread
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        Runnable sendMessage = () -> {

            while (true) {

                sendMsg.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        String msg = enterMsg.getText().toString();

                        try {
                            // write on the output stream
                            dos.writeUTF(msg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        };
        return sendMessage;
    }

    private Runnable receiveMessageFromClient() throws IOException {

        DataInputStream dis = new DataInputStream(socket.getInputStream());

        // readMessage thread
        Runnable readMessage = () -> {
            while (true) {
                try {
                    // read the message sent to this client
                    String msg = dis.readUTF();
                    viewMsg.append(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        return readMessage;
    }

    private String getLocalIpAddress() throws UnknownHostException {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipInt = wifiInfo.getIpAddress();
        System.out.println(InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress());
        return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();
    }
}

布局文件activity\u main.xml

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

    <TextView
        android:id="@+id/viewMsg"
        android:layout_width="376dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginBottom="61dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/sendMsg"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/enterMsg"
        android:layout_width="0dp"
        android:layout_height="43dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="59dp"
        android:layout_marginEnd="27dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toStartOf="@+id/sendMsg"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/viewMsg" />

    <Button
        android:id="@+id/sendMsg"
        android:layout_width="105dp"
        android:layout_height="40dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="288dp"
        android:text="Send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/enterMsg"
        app:layout_constraintTop_toBottomOf="@+id/viewMsg" />
</androidx.constraintlayout.widget.ConstraintLayout>

android维护权限

<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
 <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name = "android.permission.INTERNET"/>

这就是我试过的。我有两个问题:
我是不是用正确的方式做的(参考java客户机)
如果它是正确的,为什么我的套接字对象在握手方法中是空的
在这样做的同时,我得到了一个例外:

android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:116)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:161)
        at java.io.DataOutputStream.write(DataOutputStream.java:107)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:401)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:323)
        at com.e.chatapplication.MainActivity$1.onClick(MainActivity.java:84)
        at android.view.View.performClick(View.java:7146)
        at android.view.View.performClickInternal(View.java:7119)
        at android.view.View.access$3500(View.java:803)
        at android.view.View$PerformClick.run(View.java:27533)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7386)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)

谢谢

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题