android mobile socket open - android

Why Socket can be open on the android emulator and connect to the python server code and open a socket !! In other Hand When i run same android code on the mobile it doesn't run . didnt open a socket ..Any suggestion what is the problem and how to solve such thing
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(2048)
print rm
i=0
while (i<2):
if (rm) == row[i][0]:
reply="\n Welcome to our game %s: %s"%(rm,row[i][1])
self.sockfd.send(reply)
break
else:
i=i+1
if i==2:
reply="\n Error opaa ba2a"
self.sockfd.send(reply)
i=0
break
break
except ValueError:
self.sockfd.send("\n UNVAlied Comment ")
def run(self):
self.newClientConnect()
while True:
buff = self.sockfd.recv(2048)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '50.0.10.107'
PORT = 5807
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
print ("Server Started")
try:
serversocket.bind(('',54633))
except ValueError,e:
print e
serversocket.listen(5)
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
x=db.cursor()
x.execute("SELECT * FROM lolo")
row = x.fetchall()
print "Connected to the Database"
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
The python code and the server code it map and button when click on button connection start and it work great on the emulator

Could be a number of thing:
You don't have networking permissions enabled in your manifest file
Your wifi / 3G is disabled
If your server is on your personal computer and you're connected to the internet using a router then you need to redirect the port you're using for socket communication from the router to your machine.

If your code works on emulator but not on real phone, that could be a network issue. Emulator depends on LAN to access your server and phone access through 3G network. Is your server accessible through internet?

Related

FLUTTER can not connect to tcp SOCKET in another flutter program SocketException: Connection refused

I'm new to Dart and Flutter. I know a bit about Sockets. Here is my question:
I tried to create a TCP socket on a emulator with flutter (on android emulator Pixel 3A API 33) and connect it with another emulator(identical but diffrent emulator, Pixel 3A API 33). I got en error it says "Connection Refused (OS Error: Connection refused, errno = 111),address = 0.0.0.0, port = 36802)
I'm trying to make p2p chat application using flutter. I'm creating a socket in here in p1:
myPort = 43761;
String mysocketIP = "0.0.0.0";
final Future<ServerSocket> mySocket = ServerSocket.bind(mysocketIP, myPort);
and listening the socket like this in p1:
mySocket.then((ServerSocket listenSocket) {
listenSocket.listen((Socket mysocket) {
mysocket.listen((Uint8List data) async {
String mysocketResponse = String.fromCharCodes(data);
String strData = utf8.decode(data);
if(mysocketResponse == "///initiate"){
p2pSocket.add(utf8.encode("Got you message"));
}
print(strData);
});
});
});
All code in p1 about socket is given.
And here comes p2, which is client. Trying to connect to p1:
(I'm getting relevant port and ip from a server. That part works fine, I tested. serverResponse is the response from server. recKey means reciever's key. Its not relevant to my problem. Just another stuff.
code comes to else if block and executes but in Socket.connect line it blows.
late String recieverClientIP;
late int recieverClientPORT;
/*
...
...
*/
else if(serverResponse.length>=8 && serverResponse.substring(0,8)=="//recKey") {
targetsKey = serverResponse.substring(8);
// p2p sohbeti baslatıyoruz.
p2pSocket = await Socket.connect(recieverClientIP, recieverClientPORT);
//p2pSocket.write("///initiate");
}
;
Here is the erros message I get:
ERROR MESSAGE
I realized that in error, it says another port number. I'm using (IP 0.0.0.0) port number 47761 in p1 and in error it says another port number. Maybe it about it? I don't know I'm so confused.
By the way I'm using Android Stuido. With Emulator. Emulator I'm using is Pixel 3A API 33 x86 64
EDÄ°T: I'm using 10.2.2.2 in Server, 0.0.0.0 in p1. I can not create a socket with 10.0.2.2 in p1 it gives error. That's why I'm using 0.0.0.0 it's working.
Thanks in advance.

Python 3.5 on Windows in Bluetooth context. The requested address is not valid in its context

Code is as follows:
from bluetooth import *
import sys
if sys.version < '3':
input = raw_input
addr = None
if len(sys.argv) < 2:
print("no device specified. Searching all nearby bluetooth devices for")
print("the SampleServer service")
else:
addr = sys.argv[1]
print("Searching for SampleServer on %s" % addr)
# search for the SampleServer service
addr = "CC:79:4A:4B:35:85"
service_matches = find_service( address = addr )
if len(service_matches) == 0:
print("couldn't find the SampleServer service =(")
sys.exit(0)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print("connecting to \"%s\" at Address - %s on Port %d" % (name, host, port))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
print("connected. type stuff")
while True:
data = input()
if len(data) == 0: break
sock.send(data)
sock.close()
Run time error thrown as follows:
no device specified. Searching all nearby bluetooth devices for
the SampleServer service
connecting to "None" at Address - CC:79:4A:4B:35:85 on Port 31
Traceback (most recent call last):
File "T_C_1.py", line 40, in <module>
sock.connect((host, port))
File "C:\Python 3.5\lib\site-packages\bluetooth\msbt.py", line 72, in connect
bt.connect (self._sockfd, addr, port)
OSError: The requested address is not valid in its context.
I am unable to figure out why. Some sites tell me that my Host address need to be on the local machine....
This code resides and is run from my WIndows machine in an attempt to connect to an Android phone over Bluetooth.
I don't get why / how...
Help is appreciated!
I have run across the same error using PyBluez on Windows since I had to leave my Mac environment after receiving a bind error. I found out that the issue comes about when you are binding to a foreign IP address, or one that isn't known by your system(e.g outside public IPs). Try creating a server in PyBluez with the addr of '' and attempt to connect to that. We can further diagnose your problem from there if that doesn't work. Sorry for it not being a solid answer, I'm new to StackOverflow and I couldn't exactly comment but I wanted to offer some help.

Streaming DroidCam video to OpenCV Python in ANYWAY possible

I currently have the Droid cam Application installed on my android, it is being detected and is streaming on Skype through wifi (Droid Cam client). It is however not streaming to OpenCV, no matter what number I put in for the following.
cap=cv2.VideoCapture()
In addition to this, I have an IP address, so is there any way I can implement this so that OpenCV can read an process images wireless from my camera?
I know that it does not even begin to read the camera as I have tested it with the following code, which returns FALSE every time I run it.
cap=cv2.Videocapture(0) #Use default cam
i=0
while(i<50):
ret,frame=cap.read()
print ret
Keeps returning false, meaning camera isn't being recognized :L
You have to enter the ip address of the droidcam followed by the format.The following method worked flawlessly for me :
cap = cv2.VideoCapture('http://0.0.0.0:4747/mjpegfeed?640x480')
Make sure you open the client and do not access the camera feed elsewhere
Install Droid Cam
Enable USB Debugging
Connected camera via USB to your computer
Change IP address bellow
cap = cv2.VideoCapture('http://192.168.0.21:4747/mjpegfeed')
Its simple, droidcam app shows the url; just copy it and paste in the videocapture.
IP Cam Access:
http://192.168.29.201:4747/video
Paste the url like this :
import cv2
cap = cv2.VideoCapture('http://192.168.29.201:4747/video')
while True:
ret, frame = cap.read()
cv2.imshow("frame", frame)
cv2.waitKey(1)
Thats it. Opencv should take the feed from your droidcam.
DroidCam has an MJPEG endpoint you can try getting at,
http://ip:port/mjpegfeed
See: Reading stream from IP camera with cv2.VideoCapture()
Try
IP Webcam android app
and get frames from http://your-ip:8080/shot.jpg?
I just used the following instructions and worked for me.
Install Droidcam;
Enable USB Debugging
Connected camera via USB to your computer
Use the code:
cap = cv2.VideoCapture(0)
cap=cv2.Videocapture(0)
i=0
while(i<50):
ret,frame=cap.read() //change car -> cap
print ret
i=0
while(i<50):
#put this statement inside the loop to capture the frame returned by ip webcam or
#droidcam in every iteration
#put image address in the parameter
cap=cv2.VideoCapture('http://192.168.x.x:4747/shot.jpg?rnd=890215')
ret,frame=car.read()
print(ret)
here is the python code to do wirelessly stream video from android to opencv through droidcam
import numpy as np
import cv2
#go to the setting find ip cam username and password if it is not empty use
#first one
#cap = cv2.VideoCapture('http://username:password#ip:port/video')
cap = cv2.VideoCapture('http://ip:port/video')
while(cap.isOpened()):
ret, frame = cap.read()
#do some stuff
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Install droidcam app on PC and mobile and then write this code:
import cv2
cap =cv2.VideoCapture(1)
while True:
_, img = cap.read()
cv2.imshow("img", img)
cv2.waitKey(1)
This answer here worked for me, replacing the url with http://my-ip:8080/shot.jpg for IP Webcam app. Here is my code:
import cv2
import urllib.request
import numpy as np
my_ip = # ip given by ip-webcam
while True:
req = urllib.request.urlopen('http://'+my_ip+':8080/shot.jpg')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
if cv2.waitKey(1) == 27:
break
cv2.imshow('Its Me', img)
cv2.destroyAllWindows()

urlopen error [errno 111] connection refused

I am doing python exercise with a book 'headfirst python'
and making android app by using python and sl4a
my code is
import android
import json
import time
from urllib import urlencode
from urllib2 import urlopen
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes:'
quit_msg = "Quitting Coach Kelly's App."
web_server = 'http://127.0.0.1:8080'
get_names_cgi = '/cgi-bin/generate_name.py'
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url, urlencode(post_data))
else:
page = urlopen(url)
return(page.read().decode("utf8"))
app = android.Android()
def status_update(msg, how_long=2):
app.makeToast(msg)
time.sleep(how_long)
status_update(hello_msg)
athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi)))
app.dialogCreateAlert(list_title)
app.dialogSetSingleChoiceItems(athlete_names)
app.dialogSetPositiveButtonText('Select')
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
resp = app.dialogGetResponse().result
status_update(quit_msg)
this is my code and the result is
what is the problem???
I can not figure out what the problem is...
Use 10.0.2.2:8080
because If you are running both server and emulator in you computer 127.0.0.1:(port) the local IP will refer to the emulator then you need another local IP for the server which will be automatically The 10.0.2.2
hope i clearified it well, glad i helped
Having followed #Coderji 's solution, I was finally able to solve this problem albeit with a different IP address; since the suggested 10.0.2.2 didn't work for me.
What worked for me was to access a terminal, ipconfig, and then used any of the provided ipv4 addresses provided by cmd (all of them seemed to work). Cheers.

android bluetooth serversocket with python-bluez client

I am trying to connect my laptop(as client) to my android phone(as listener) using python-bluez on the laptop and android-bluetooth API on the phone.
I use the following code for my phone:
BluetoothServerSocket tmp = badapter.listenUsingRfcommWithServiceRecord(
badapter.getName(), MY_UUID);
BluetoothServerSocket bserversocket = tmp;
if(bserversocket != null)
{
BluetoothSocket acceptsocket = bserversocket.accept(timeout);
}
//timeout is set to about 15 sec
if(acceptsocket != null)
{
out.append("got the connection...\n");
}
and the following in python for my laptop client:
from bluetooth import *
btooth_addr = "38:EC:E4:57:1F:1B"
sock = BluetoothSocket(RFCOMM)
sock.connect((btooth_addr, 2))
print "Connected"
sock.close()
the listener time-outs without acknowledging any connections from the laptop, while the sender moves on to print 'Connected' on all attempts on different ports.
the problem is that I don't know and can't set the port/channel the android phone is listening on, and also that I am required to fill in a port number as second argument of 'connect'(2 in this snippet).
please help me out - my sole goal at this time is to get the connection attempt acknowledged by the phone.
Have a look at the pybluez documentation(source code) for establishing client connections.
You can get the correct port for the supplied Bluetooth address and UUID using find_service.
Then connect your socket just as you do in your code, replacing hardcoded port value with the correct one.
Don't forget to vote up!

Categories

Resources