我正在尝试使用WiFi将手机连接到笔记本电脑。两个设备都连接到一个网络。笔记本电脑有IP 192.168.1.35所以我试图通过智能手机连接该IP(防火墙已关闭)。这是代码:
package org.me.androidapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
Toast.makeText(this.getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Socket socket = new Socket("192.168.1.35", 9999);
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("dupa");
socket.close();
} catch (UnknownHostException ex) {
Toast.makeText(this.getApplicationContext(), "Nie odnaleziono hosta", Toast.LENGTH_LONG).show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Toast.makeText(this.getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我使用此代码(用python编写)作为服务器:
import socket
_connector = None
_running = True
_host = 'localhost'
_port = '9999'
_maxClient = 999
debug = True
_policyFile = '<?xml version="1.0" encoding="UTF-8"?><cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd"><allow-access-from domain="*" to-ports="*" secure="false" /><site-control permitted-cross-domain-policies="master-only" /></cross-domain-policy>'
## Trace debugging messages.
# @param aString String to be printed.
def printd( aString ):
if debug:
print aString
_connector = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
_connector.bind ( ( str(_host), int(_port) ) )
_connector.listen ( int(_maxClient) )
_running = True
while _running:
printd('Running on port ' + _port + ' ... ')
channel, details = _connector.accept()
if _running:
printd( 'New connection with: ' + str(details) )
channel.setblocking( 1 )
recvData = channel.recv(2000)
if("policy-file-request" in recvData):
channel.send(_policyFile)
printd( 'host: ' + str(details[0]) )
printd( 'port: ' + str(details[1]) )
printd( 'port: ' + str(int(details[1])) )
channel.close()
我在手机上测试这个应用程序因为我不确定如何配置模拟器(任何帮助?:))。电话显示错误“Java.Net.ConnectionError localhost / 192.168.1.1:9999 - 连接被拒绝”。我想知道为什么它显示IP 192.168.1.1 ...
请帮忙, 克里斯
答案 0 :(得分:5)
您的python代码绑定到localhost,这意味着它不是在网络上监听,而是仅在环回上监听,因此您应该更改它以使其监听计算机的网络地址(即192.168.1.35)而不是127.0.0.1