简体   繁体   English

如何在windows中使用Socket发送消息From Android to python application

[英]How to send message From Android to python application in windows using Socket

I am trying to send message from the android app to the python application in windows but it is not working.我正在尝试将消息从 android 应用程序发送到 windows 中的 python 应用程序,但它不起作用。

Android app is working good but client created in windows using python is not starting it is showing error that:- Traceback (most recent call last): File "client.py", line 14, in s.connect((socket.gethostname(), 9876)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Android 应用程序运行良好,但在 windows 中使用 python 创建的客户端未启动,它显示的错误是:- Traceback(最后一次调用):文件“client.py”,第 14 行,在 s.connect((socket.gethostname( ), 9876)) ConnectionRefusedError: [WinError 10061] 由于目标机器主动拒绝,无法建立连接

Here is my client.py file这是我的 client.py 文件

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import socket


# In[2]:


s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9876))


# In[ ]:

while True:
    msg = s.recv(1024)
    print(msg.decode("utf-8"))

Here is my messageSender.java in android这是我在 android 中的 messageSender.java

package com.example.sockets;

import android.os.AsyncTask;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class MessegeSender extends AsyncTask<String,Void,Void> {
    Socket socket;
    DataOutputStream dataOutputStream;
    PrintWriter printWriter;


    @Override
    protected Void doInBackground(String... strings) {
        String message=strings[0];

        try {
            socket = new Socket("192.168.1.6",9876);
            printWriter= new PrintWriter(socket.getOutputStream());
            printWriter.write(message);
            printWriter.flush();
            printWriter.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Here is my Mainactivity.java file in android这是我在 android 中的 Mainactivity.java 文件

package com.example.sockets;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=(EditText) findViewById(R.id.msgBox);
    }

    public void sendMsg(View view)
    {
        Toast.makeText(this, "Function is running", Toast.LENGTH_SHORT).show();
        MessegeSender messegeSender =new MessegeSender();
        messegeSender.execute(editText.getText().toString());
    }
}

if you want to connect android app to python via sockets then do same as above in android but change the python file by -如果你想通过 sockets 将 android 应用程序连接到 python,那么在 android 中执行与上面相同的操作,但将 python 文件更改为 -

#Imports Modules
import socket
import time

listensocket = socket.socket()
Port = 9876
maxConnections = 2
IP = socket.gethostname() #Gets Hostname Of Current Macheine

listensocket.bind(('',Port))

#Opens Server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))

#Accepts Incoming Connection
# (clientsocket, address) = listensocket.accept()
# print("New connection made!")

# running = True


#Main
while True:
    (clientsocket, address) = listensocket.accept()
    message = clientsocket.recv(1024).decode() #Receives Message
    print(message) #Prints Message

    # if not message == "":
    #    print(message) #Prints Message
      
    #Closes Server If Message Is Nothing (Client Terminated)
    # elif message =="":
    #     clientsocket.close()
    #     # running = False

I'm not sure of the exact situation, but if you are trying to connect over the inte.net you may want to look into this permission, or permissions like this one.我不确定具体情况,但如果您尝试通过 inte.net 进行连接,您可能需要查看此权限或类似权限。

Android has a layer of security which does not allow connections unless the user using application grants the application permission. Android 有一个安全层不允许连接,除非使用应用程序的用户授予应用程序权限。 Look into the permissions for this.查看此权限。 My answer may be just a starting point.我的回答可能只是一个起点。

<uses-permission android:name="android.permission.INTERNET" />

Here are some resources:这里有一些资源:

How to add manifest permission to an application? 如何向应用程序添加清单权限?

how to create Socket connection in Android? 如何在 Android 中创建 Socket 连接?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM