android socket连接与raspberry pi

2024-05-20 17:59:25 发布

您现在位置:Python中文网/ 问答频道 /正文

Android客户端代码使用sockets连接到raspberry pi上的python脚本

 public class SendMessage extends AsyncTask<String,Void,Void>{
    private Exception exception;
    @Override
    protected Void doInBackground(String... params) {
        try{
            Socket socket = new Socket("192.168.0.3",1234);
            PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            outToServer.print(params[0]);
            outToServer.flush();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch(Exception e){
            this.exception = e;
            return null;
        }
        return null;
    }
}

清单文件中的Internet权限:

^{pr2}$

服务器代码:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.bind(("192.168.0.3",1234))
 except socket.error as err:
    print "Build failed, Error: "+str(err[0])+",Message: "+err[1]
    sys.exit()

 print "socket build success"
 s.listen(5)
 while True:
     c,addr = s.accept()
     print "got connection from ",addr
     buf = conn.recv(64)
     print buf

c.关闭()

我得到一个错误的安卓说

java.net.SocketException: socket failed: EACCES (Permission denied)

Tags: 代码newstringexceptionsocketparamserrprint