问题描述
我正在尝试创建一个聊天应用程序。服务器是用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_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 Mainfest权限
<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"/>
这是我尝试过的。我有两个问题:
在这样做的同时,我得到了异常:
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)
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)