用Python服务器和Android客户端进行Socket编程
我想设置一个套接字接口。PC端运行一个用Python编写的非常简单的套接字服务器来测试连接:用Python服务器和Android客户端进行Socket编程,android,python,sockets,Android,Python,Sockets,我想设置一个套接字接口。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 mach
#!/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上的端口上没有侦听内容
- 服务器端有一个本地防火墙正在阻止该连接尝试
- 您没有使用WIFI,因此您不在同一网络下
tcpdump
可能会有帮助;在Windows系统下,WireShark
可能会有用)
如果您使用的是公共IP,那么总结一下路由器阻塞防火墙,这意味着该端口可能在服务器端被关闭/过滤,只需打开它即可
所有这些都假设您在AndroidManifest.xml文件中拥有android.permission.INTERNET权限。您必须在代码中输入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用户处获取输入和端口号即可
编辑文本,您只需复制并粘贴代码
享受吧!
如果没有再在这里工作岗位 您正在socket.gethostname()上运行服务器,并且正在尝试将android应用程序连接到
“192.168.2.184”
尝试在此地址上运行服务器
s = socket.socket()
host = "192.168.2.184"
port = 5000
s.bind((host, port))
“我无法在个人电脑和安卓设备之间建立连接”是非常模糊的。这是一个例外吗?如果是这样的话,你能用LogCat更新你的问题吗?PC可能有一个防火墙阻止进入的连接;Windows防火墙或McAfee/Symantec/等。请尝试关闭它们并重新测试。如果这不起作用,那么同时测试双方就更难了,看看你是否能证明一方有效,然后另一方有效。在Android设备上,您可以打开web浏览器并转到
http://192.168.2.184:5000/
并查看它是否能连接。它甚至可能会显示您的“感谢连接”信息。如果这样做有效,您就知道您的客户端代码出错,如果这样做不起作用,您就知道您的网络连接或服务器代码不正确。通过Android设备上的web浏览器()访问时,它会连接到服务器。好的,现在我可以建立连接了。