android - 使用 Python 服务器和 Android 客户端进行套接字编程

标签 android python sockets

我想设置一个套接字接口(interface)。 PC 端运行一个用 Python 编写的非常简单的套接字服务器来测试连接:

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

Android 客户端应用程序将连接到 PC:

package com.example.androidsocketclient;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 5000;
    private static final String SERVER_IP = "192.168.2.184";

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

        new Thread(new ClientThread()).start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }

}

但是,我无法在 PC 和 Android 设备之间建立连接。有什么办法解决这个问题吗?

最佳答案

你必须在你的代码中输入 ip 地址和端口号没有 ip 地址和端口号它在哪里??请看下面的例子:

public void connect() {
      new Thread(new Runnable(){

        @Override
        public void run() {
            try {

                client = new Socket(ipadres, portnumber);

                printwriter = new PrintWriter(client.getOutputStream(), true);
                printwriter.write("HI "); // write the message to output stream
                printwriter.flush();
                printwriter.close();
                connection = true;
                Log.d("socket", "connected " + connection);

                // Toast in background becauase Toast cannnot be in main thread you have to create runOnuithread.
                // this is run on ui thread where dialogs and all other GUI will run.
                if (client.isConnected()) {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            //Do your UI operations like dialog opening or Toast here
                         connect.setText("Connected");
                            Toast.makeText(getApplicationContext(), "Messege send", Toast.LENGTH_SHORT).show();
                        }
                    });
                                        }
            }
            catch (UnknownHostException e2){
                   MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //Do your UI operations like dialog opening or Toast here
                        Toast.makeText(getApplicationContext(), "Unknown host please make sure IP address", Toast.LENGTH_SHORT).show();
                    }
                });

            }
            catch (IOException e1) {
                Log.d("socket", "IOException");
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //Do your UI operations like dialog opening or Toast here
                        Toast.makeText(getApplicationContext(), "Error Occured"+ "  " +to, Toast.LENGTH_SHORT).show();
                    }
                });
            }

        }
    }).start();
}

只需使用 ipadress 和端口号的用户输入 编辑文本,您只需复制并粘贴代码

尽情享受吧! 如果没有在这里再次工作。

关于android - 使用 Python 服务器和 Android 客户端进行套接字编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271207/

相关文章:

android - 使用相机拍照,将其保存在本地——而不是 SD 卡

android - 预验证类中的 java.lang.IllegalAccessError 类引用解析为意外实现

Python dir命令确定方法

.net - .NET 中的 TCP 连接质量

c++ - 使用 boost 库构建 socket.io C++

android - Facebook 移动应用安装广告预览链接错误

android - 如何将流程输出链接到textview并实时自动更新?

如果尝试读取其输出,Python 子进程会挂起

python - 如何从 cookiejar 中形成 Cookie header ?

c# - 反序列化异常: Unable to find assembly