简体   繁体   中英

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 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

Here is my client.py file

#!/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

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

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 -

#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.

Android has a layer of security which does not allow connections unless the user using application grants the application permission. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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