[英]Send message from Android Client to Python Server
嗨,我正在嘗試將數據從 android 客戶端發送到我 PC 上的 Python 服務器,這是代碼我真的不知道我做錯了什么(我不確定我是否理解 tcp 套接字如何在 Javascript 上工作),我是編碼新手,當我的手機通過 USB 連接到 PC 時,我運行這個程序。
Javascript客戶端:
package com.example.app;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.idBtn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"should do something",Toast.LENGTH_SHORT).show();
BackgroundTask b = new BackgroundTask();
b.execute();
}
});
}
class BackgroundTask extends AsyncTask<String,Void,String>
{
Socket s;
DataOutputStream dos;
String message;
@Override
protected String doInBackground(String... strings) {
message = "Hello_Javascript";
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.7");
s = new Socket(serverAddr, 10000);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(message);
dos.close();
}catch(IOException e){
e.printStackTrace();
}
return null;
}
}
}
Python 服務器(應該沒問題,因為我可以與另一個 Python 客戶端通信)
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up port ', server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from ', client_address)
# Receive the data in small chunks and retransmit it
data = connection.recv(100)
print('received ', data)
finally:
# Clean up the connection
connection.close()
先感謝您!
您可以使用模擬器來檢查它是否有效。因為兩者都以這種方式共享同一服務器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.