gpt4 book ai didi

java - 客户端(Java)未连接到服务器(Kotlin)Android Studio,出了什么问题?

转载 作者:行者123 更新时间:2023-12-02 12:56:17 25 4
gpt4 key购买 nike

客户端代码 100% 正常工作,因为我用它连接到别人制作的服务器。现在我尝试制作自己的服务器。有人知道为什么这不起作用吗?我在服务器应用程序中没有收到任何错误,但它永远无法进入第二个线程。

客户端代码:

public void connectToServer(){ (used in some activity)
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
socket = new Socket("192.168.0.1", 9999);
send = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
get = new BufferedReader(new InputStreamReader(socket.getInputStream()));

}catch (Exception ex){
Log.e("connection", ex.toString());
}
return null;
}
}.execute();
}

服务器代码:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

findViewById<Button>(R.id.buttonStartServer).setOnClickListener {
Log.e("Button", "Apasat")
val server = ServerSocket(9999, 10, InetAddress.getByName("0.0.0.0"))
thread {
run {
Log.e("first run check server", server.inetAddress.hostAddress)
Log.e("first run", "waiting for clients")
while (true) {
val client = server.accept()

Log.e("first run", "got a client")
thread {
run {
Log.e("second run", "waiting for messages")
val reader = Scanner(client.getInputStream())
val writer: OutputStream = client.getOutputStream()
while(true) {
try {
val text = reader.nextLine()
writer.write((text + '\n').toByteArray(Charset.defaultCharset()))
}catch (ex: Exception){
Log.e("client" + client.inetAddress.hostAddress, ex.toString())
}
}
}
}
}
}
}
}
}
}

最佳答案

代码工作正常,但因为我的服务器也在 android 上运行,所以我需要像这里一样设置服务器设备模拟器: https://developer.android.com/studio/run/emulator-networking#connecting

有人在这里询问如何设置: Communication between two Android emulators他在哪里得到了解释的步骤。

关于java - 客户端(Java)未连接到服务器(Kotlin)Android Studio,出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62313667/

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