使用Python服务器和Android客户端进行套接字编程 [英] Socket Programming with Python server and Android client

查看:162
本文介绍了使用Python服务器和Android客户端进行套接字编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to setup a socket interface. PC side runs a very simple socket server written in Python to test the connection:

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

An Android client application will connect to 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设备之间建立连接.有解决这个问题的主意吗?

However, I cannot establish a connection between PC and Android device. Any idea to fix this?

推荐答案

由于尚未使用私有IP或公共IP,因此可能不存在以下问题:

As you haven't detailed if you're using either private or public IPs, it might be any of the following issues:

如果您使用的是专用连接,那么很明显这不是路由器防火墙相关的问题,因为您位于同一网络中,因此只有几种可能性:

If you're using private connections, it's obvious it's not a router-firewall related problem as you are under the same net, so there are only a few possibilities:

  • 在服务器端该IP上的该端口上没有监听
  • 服务器端有一个本地防火墙阻止了该连接尝试
  • 您没有使用WIFI,因此您不在同一网络中.

您应该确保可以通过某种方式打开该服务,这将有助于您调试问题的出处.如果您已经完成此操作,建议您使用一些调试工具来跟踪TCP数据包(我不知道您在目标计算机上使用哪种操作系统;如果是Linux发行版,则 tcpdump 可能会有所帮助;在Windows系统下, WireShark 可能会有用).

You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you've already done this, I'd suggest using some debugging tool to trace TCP packets (I don't know either what kind of operating system you use on the destination machine; if it's some linux distribution, tcpdump might help; under Windows systems, WireShark might be useful).

如果您使用的是公共IP,请总结一个路由器阻止防火墙,这意味着该端口可能在服务器端已被关闭/过滤,只需打开它即可.

If you're using public IPs, sum up a router blocking firewall, which means that this port might be closed/filtered on the server side, just open it.

所有假设您在AndroidManifest.xml文件中拥有 android.permission.INTERNET 权限.

All that assuming you have the android.permission.INTERNET permission in your AndroidManifest.xml file.

这篇关于使用Python服务器和Android客户端进行套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆