java - Android 无法使用 Java 在套接字中发送两次 PrintWriter 消息。也可以发送 Python 代码而不是给我发送 Java 代码
问题描述
我创建了一个将命令发送到我使用 Python 编写的服务器的代码。该代码只工作一次(服务器收到我第一次发送的内容),但第二次似乎没有发送任何内容,因为服务器没有收到新信息,它一直在等待新信息。我的代码:
StringBuilder Data = new StringBuilder(); // The Data to send
public void Send(View view) {
Thread send = new Thread() {
@Override
public void run() {
try {
Socket socket = new Socket("20.7.65.2", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue(View view) {
Data.append("Hello from client"); // Append to "Data"
Send(null); // Run the send functionn (again)
}
}
我的 Python 服务器:
import socket, time
soc = socket.socket()
soc.bind((socket.gethostname(), 6398))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
while True:
message = client.recv(1024).decode()
if(message != ""):
print(message)
time.sleep(0.1)
简而言之,我尝试运行两次 run 函数。第一次发送到服务器并收到信息,第二次服务器仍在等待信息,没有收到我再次发送的信息。也许是因为他无法接收所有客户发给他的所有消息
也可以代替向我发送 Java 代码来发送可以工作并接收来自所有客户端的所有消息的 Python 代码
解决方案
在您的代码中,服务器只接受一次连接,然后从同一个客户端接收。但是根据您的问题,我认为您的服务器应该能够监听多个客户端,因此您可以在服务器中使用多线程。我没有使用客户端线程,而是使用了单击时与服务器连接的按钮。我也无法理解线程客户端的需要。如果您认为答案需要进行一些更改,您可以发表评论。
这是python服务器
import socket, time
import threading
soc = socket.socket()
# print(socket.)
soc.bind(("192.168.1.5", 6398))
soc.listen(5)
def info(client):
message = client.recv(1024).decode()
if(message != ""):
print(message)
return
while True:
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
threading.Thread(target=info,args=(client,)).start()
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
StringBuilder Data = new StringBuilder(); // The Data to send
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= findViewById(R.id.connectBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Continue();
}
});
}
public void Send() {
Thread send = new Thread() {
@Override
public void run() {
try {
Socket socket = new Socket("192.168.1.5", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue() {
Data.append("Hello from client"); // Append to "Data"
Send(); // Run the send functionn (again)
}
}
不要忘记添加AndroidManifest.xml<uses-permission android:name="android.permission.INTERNET"/>
。
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">
<Button
android:id="@+id/connectBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
推荐阅读
- javascript - 与胖箭头 (=>) 功能混淆
- vue.js - 如何使用 vue 路由器在 Vuejs 方法中获取 baseURL?
- json - 如何在尝试解码 JSON 时修复 Xcode 中的错误“不匹配”
- android-studio - Flutter Android Studio 光标闪烁问题。无法输入文字
- sql - 用于检查另一个表列的值的 SQL 约束
- python - 如何使用 Pandas 对相似的字符串值进行分组,并创建一个新列,其中相似的值都获得相同的标签?
- css - 本地字体未在 .scss 文件中导入
- javascript - Power Bi Embedded:有没有办法设置 onFullscreen 事件处理程序?
- neural-network - 如何在 pytorch 模型中声明每个神经元连接?
- google-cloud-functions - 如何在另一个函数中正确调用谷歌云函数