gpt4 book ai didi

java - Android 上的 TCP 套接字连接被拒绝

转载 作者:行者123 更新时间:2023-12-01 19:46:12 24 4
gpt4 key购买 nike

在一个简单的客户端-服务器 TCP 套接字中,当我尝试在 Android Studio 中创建客户端套接字时遇到问题。导致错误的指令是Socket s=new Socket(hostname,port);

我使用的端口是 1993,我尝试了 hostname 变量的一些值:

  1. 主机名=“127.0.0.1”
  2. 主机名=“localhost”
  3. 主机名=""
  4. hostname=InetAddress.getByName([with-前 2 个值])

在每种情况下,应用程序都会因为此错误而停止,下面的错误属于第一点,其他错误都会出现类似的错误。

    W/System.err: Couldn't get I/O for the connection to 127.0.0.1    W/System.err: java.net.ConnectException: failed to connect to /127.0.0.1 (port 1993): connect failed: ECONNREFUSED (Connection refused)            at libcore.io.IoBridge.connect(IoBridge.java:124)            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)            at java.net.Socket.startupSocket(Socket.java:592)            at java.net.Socket.tryAllAddresses(Socket.java:128)            at java.net.Socket.(Socket.java:178)            at java.net.Socket.(Socket.java:150)    W/System.err:     at com.example.davide.beachapp.model.ClientSocket$MyThread.run(ClientSocket.java:92)        Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)            at libcore.io.Posix.connect(Native Method)            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)            at libcore.io.IoBridge.connectErrno(IoBridge.java:137)            at libcore.io.IoBridge.connect(IoBridge.java:122)            ... 7 more

The same instruction in Eclipse works, I tested it with a server "nc -l 1993" on the command-line and everything works on Eclipse.

Maybe it's some configuration problem with the manifest?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.davide.beachapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" >
</intent-filter>
</activity>
</application>
</manifest>

最佳答案

如果您使用的是模拟器,请尝试使用 10.0.2.2 而不是 127.0.0.1

有关更多信息,请访问此页面:

Set up Android Emulator networking

关于java - Android 上的 TCP 套接字连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com