我已经制作了一个简单的聊天应用程序,用于在Java中与服务器一起在桌面上使用。现在,我将桌面应用程序重新构建为Android应用程序。唯一的问题是我无法连接到服务器。它在后台不起作用,因此我尝试了一个按钮,但仍然没有结果。
我正在eclipse中运行服务器,并在带有模拟器的android studio中运行应用。
重要说明:它显示错误:
[HttpPost(EndpointUrlConstants.MY_ENDPOINT)]
public async Task<IActionResult> DoSomething([FromBody] MyModel myModel)
{
// Some Code
return this.Ok();
}
代码如下:
08-01 18:00:57.255 8914-8914/com.example.android.chatnow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.chatnow, PID: 8914
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.chatnow/com.example.android.chatnow.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:355)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:357)
at java.net.Socket.connect(Socket.java:616)
at java.net.Socket.connect(Socket.java:565)
at java.net.Socket.<init>(Socket.java:445)
at java.net.Socket.<init>(Socket.java:217)
at com.example.android.chatnow.MainActivity.setUpNetworking(MainActivity.java:29)
at com.example.android.chatnow.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
和XML:
package com.example.android.chatnow;
import java.io.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.net.*;
public class MainActivity extends AppCompatActivity {
BufferedReader reader;
PrintWriter writer;
Socket sock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
}
public void onSendMessage(View view) {
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
//writer.println(": " +messageText);
//writer.flush();
}
public void setUpNetworking(View view) {
try {
sock=new Socket("10.0.2.2", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
Log.d("NiceTag", "Net established");
}catch (Exception ex){
ex.printStackTrace();
Log.d("NiceTag", "Net failed");
}
}
public class IncomingReader implements Runnable{
public void run() {
String message;
try {
while ( (message=reader.readLine())!=null) {
TextView messageView = (TextView)findViewById(R.id.displaymessage);
messageView.append( message + '\n');
}
System.out.println("!while");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
此外,清单:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/displaymessage"
android:layout_width="262dp"
android:layout_height="401dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="40dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/displaymessage" />
<Button
android:id="@+id/sendbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="36dp"
android:text="Send"
android:onClick="onSendMessage"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.469"
app:layout_constraintStart_toEndOf="@+id/message"
app:layout_constraintTop_toBottomOf="@+id/displaymessage" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Connect"
android:onClick="setUpNetworking"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/displaymessage"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
P.S。服务器和模拟器在同一设备上运行
答案 0 :(得分:0)
假设您的Android应用程序在本地计算机上的Emulator中运行,并且服务器在同一计算机上运行,那么localhost
将不会引用您的服务器应用程序。如果要引用服务器应用程序,则应调用以下IP地址:10.0.2.2
来自与服务器在同一台计算机上运行的仿真器。
当您从物理设备调用服务器,然后通过终端中的ifconfig
命令(或Windows上的ipconfig
)找到您的IP地址时,可通过以下方式将移动设备连接到与服务器相同的本地网络: WiFi,并在您的Android应用中使用适当的IP地址。
编辑
上次编辑后,问题更加明显。 您有两个问题:
10.0.2.2
而不是
localhost
AsyncTask
(请参阅官方文档以了解如何使用此类)答案 1 :(得分:0)
起初,我执行了您的代码,但最终出现以下异常:
android.os.NetworkOnMainThreadException 这意味着您必须将代码从主线程迁移到工作线程或后台线程。
一种方法是引入AsyncTask
如下:
private class ConnectSimpleServerTask extends AsyncTask<Void, Void, Void> {
private Socket sock;
private ConnectSimpleServerTask(Socket sock) {
this.sock = sock;
}
@Override
protected Void doInBackground(Void... voids) {
try {
sock=new Socket("10.0.2.2", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
Log.d("NiceTag", "Net established");
}catch (Exception ex){
ex.printStackTrace();
Log.d("NiceTag", "Net failed");
}
return null;
}
}
并在您的setUpNetworking
中,执行以下操作:
public void setUpNetworking(View view) {
new ConnectSimpleServerTask(sock).execute();
}
这只是一个起点,您可以根据需要修改AsyncTask
。然后,在使用当前工作线程执行后,
套接字obj仍然为空,这意味着主机或端口有问题。
我发现this answer可能会帮助您设置正确的主机和端口,请看一下。
答案 2 :(得分:0)
我解决了。我将Exception修改为IOException。之后,我为setUpNetworking创建了一个线程!谢谢大家的回答! :)