简体   繁体   中英

TCP/IP on an Android Device using Python Socket

I have a Python script that is running on Android-SL4A that returns the values from the orientation sensor. I would like to transfer those values as text to a raspberry pi 2B+. While I have some Python skills I am unfamiliar with TCP/IP but I found this code below, and similar code to run on the receiving device. While testing the code below, the listening code on a Windows PC appears to be listening just fine but when I execute the sending code (posted below) on the Android device it gives a error at s.connect((TCP_IP, TCP_PORT)) I receive an error(Errno 111) that the connection was refused. Any help debugging would be great.

import time, math, sys, traceback
import socket
print "imports done"
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
print "settings defined"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "socket created"
s.connect((TCP_IP, TCP_PORT))
print "connection made"
print "message sent"
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
print "All Done" 

If you don't want to learn how low-level sockets work, you can always use someone else's library.

The popular ones with TCP support are Tornado and Twisted, but I suggest you use simpleTCP , as it doesn't require you learn an entire framework to simply send information over TCP. The project website has the 5-line program for an echo server and an even smaller example of client sockets on its front page.

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