我正在尝试开发一个应用程序,其中android客户端通过Socket编程从Python服务器发送和接收数据。没有错误也没有任何异常崩溃但我的客户端无法访问python服务器,因为我的服务器没有从任何客户端接收任何连接。我关闭了我的Windows防火墙,以便我的电脑不会阻止未知的访问。我尝试在堆栈交换中引用类似的文章,但他们都说他们正在接收来自客户端的连接。请告诉我我的代码有什么问题。 先感谢您。 (在我的服务器代码中,如果我使用我的PC的IP地址,那么它显示错误10049,所以我使用的是localhost IP)
/*Client side code- Android*/
public void onResults(Bundle bundle) {
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.get(0) != null)
{
final String text = matches.get(0);
Thread t = new Thread(){
@Override
public void run() {
try {
Socket s = new Socket("47.11.229.90",25001);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(text);
//read input stream
DataInputStream dis2 = new DataInputStream(s.getInputStream());
InputStreamReader disR2 = new InputStreamReader(dis2);
BufferedReader br = new BufferedReader(disR2);//create a BufferReader object for input
//print the input to the application screen
String replyMsg = br.toString();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
//String random = (helloMessages[new Random().nextInt(helloMessages.length)]);
ts.speak(replyMsg, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
//tvr.setText("Hey");
//final TextView receivedMsg = (TextView) findViewById(R.id.textView2);
//receivedMsg.setText(br.toString());
dis2.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
t.start();
Toast.makeText(MainActivity.this, "Sending data: " + text, Toast.LENGTH_LONG).show();
/*
if (text.equalsIgnoreCase("Hi") || text.equalsIgnoreCase("Hello") || text.equalsIgnoreCase("Hey") || text.equalsIgnoreCase("Hello Pi") || text.equalsIgnoreCase("Hi Pi") || text.equalsIgnoreCase("Hey Pi"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (helloMessages[new Random().nextInt(helloMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Hey");
}
else if (text.equalsIgnoreCase("Who are you") || text.equalsIgnoreCase("Introduce Yourself") || text.equalsIgnoreCase("Tell me something about yourself") || text.equalsIgnoreCase("Describe yourself"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (introMessages[new Random().nextInt(introMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Hey this is Doctor Pi");
}
else if (text.equalsIgnoreCase("I love you")|| text.equalsIgnoreCase("I am in love with your voice") || text.equalsIgnoreCase("Hey Akanksha"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
ts.speak("I Love you too", TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("I Love you too");
} else {
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (sorryMessages[new Random().nextInt(sorryMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Sorry!");
}*/
}
else{
Toast.makeText(MainActivity.this,"Null string received",Toast.LENGTH_LONG).show();
}
//for (String result : matches)
// text += result;
}
/*Server side code-Python*/
import sqlite3
import nltk
from nltk.tokenize import word_tokenize
from socket import *
HOST = "127.0.0.1" #local host IT SHOWS AN ERROR WHEN I USE MY PC's IP ADDRESS 47.11.229.90
PORT = 25001 #open port 18000 for connection
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
print("Hello")
s.listen(1) #how many connections can it receive at one time
connect_device, addr = s.accept() #accept the connection
print("Connected by: ",addr)
while True:
print("In the loop")
data = connect_device.recv(1024) # how many bytes of data will the server receive
data = data.decode('utf-8')
print("Received: ", repr(data))
conn = sqlite3.connect("ciao.db")
c=conn.cursor()
#string = "Hey tell me something about dengue"
#string2 = string.lower()
string = repr(data)
string2 = string.lower()
list_items = word_tokenize(string2)
print("List items = ",list_items)
Greetings = ['hi', "hey"]
c.execute("SELECT Disease_Name FROM ciao")
data = c.fetchall()
data2 = []
for i in data:
for j in i:
if j is not None:
data2.append(j)
print("data2 = ",data2)
msg = ""
print("loop starts")
for i in list_items:
print(i)
print("Data = ",data2)
if i in data2:
if 'symptoms' in list_items:
c.execute("SELECT Symptoms from ciao WHERE Disease_Name = (?)",(i,))
sym = c.fetchall()
for j in sym:
for k in j:
msg += k + " "
if 'remedial' in list_items:
c.execute("SELECT Remedial_Measures from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'medicines' in list_items:
c.execute("SELECT Medicines from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'diagnostic' in list_items:
c.execute("SELECT Diagnostic_tests from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'hospitals' in list_items:
c.execute("SELECT Related_Hospitals from ciao WHERE Disease_Name = (?)",(i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if not('symptoms' in list_items) and not('remedial' in list_items) and not('medicines' in list_items) and not('diagnostic' in list_items) and not('hospitals' in list_items):
c.execute("SELECT * from ciao WHERE Disease_Name = (?)",(i,) )
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
else:
if i in Greetings:
if len(list_items) == 1 or len(list_items) == 0:
msg = "Hello I am Pi"
if msg == "":
msg = "Sorry"
print(msg)
connect_device.sendall(msg)
conn.close()
connect_device.close()
答案 0 :(得分:0)
我的python代码在Pycharm上运行,因此我必须在管理员模式下运行它,并确保使用try和except块来包围bind函数。每次运行程序时都要更改端口号,并在首次执行之前关闭Windows防火墙,将PC的IP地址用作主机地址。现在它有效 -
/*Client side- Android text to speech's onResult*/
@Override
public void onResults(Bundle bundle) {
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.get(0) != null)
{
final String text = matches.get(0);
Thread t = new Thread(){
@Override
public void run() {
try {
Socket s = new Socket("192.168.43.123",9999);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(text);
//read input stream
DataInputStream dis2 = new DataInputStream(s.getInputStream());
InputStreamReader disR2 = new InputStreamReader(dis2);
BufferedReader br = new BufferedReader(disR2,65536);//create a BufferReader object for input
//print the input to the application screen
//final String replyMsg = br.toString();
final String replyMsg = br.readLine();
//String receivedMsg = new String(replyMsg);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,replyMsg, Toast.LENGTH_LONG).show();
}
});
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
//String random = (helloMessages[new Random().nextInt(helloMessages.length)]);
ts.speak(replyMsg, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
//tvr.setText("Hey");
//final TextView receivedMsg = (TextView) findViewById(R.id.textView2);
//receivedMsg.setText(br.toString());
dis2.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
t.start();
Toast.makeText(MainActivity.this, "Sending data: " + text, Toast.LENGTH_LONG).show();
/*
if (text.equalsIgnoreCase("Hi") || text.equalsIgnoreCase("Hello") || text.equalsIgnoreCase("Hey") || text.equalsIgnoreCase("Hello Pi") || text.equalsIgnoreCase("Hi Pi") || text.equalsIgnoreCase("Hey Pi"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (helloMessages[new Random().nextInt(helloMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Hey");
}
else if (text.equalsIgnoreCase("Who are you") || text.equalsIgnoreCase("Introduce Yourself") || text.equalsIgnoreCase("Tell me something about yourself") || text.equalsIgnoreCase("Describe yourself"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (introMessages[new Random().nextInt(introMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Hey this is Doctor Pi");
}
else if (text.equalsIgnoreCase("I love you")|| text.equalsIgnoreCase("I am in love with your voice") || text.equalsIgnoreCase("Hey Akanksha"))
{
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
ts.speak("I Love you too", TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("I Love you too");
} else {
//new RetriveByteArray().execute("https://raw.githubusercontent.com/felixpalmer/android-visualizer/master/demo/demo-3.gif");
//gif.startAnimation();
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
String random = (sorryMessages[new Random().nextInt(sorryMessages.length)]);
ts.speak(random, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
pulseView.startPulse();
tvr.setText("Sorry!");
}*/
}
else{
Toast.makeText(MainActivity.this,"Null string received",Toast.LENGTH_LONG).show();
}
//for (String result : matches)
// text += result;
}
/*Server side code- Python server*/
import sqlite3
import nltk
from nltk.tokenize import word_tokenize
from socket import *
import sys
import socket
HOST = "192.168.43.123" #local host IT SHOWS AN ERROR WHEN I USE MY PC's IP ADDRESS 47.11.229.90 127.0.0.1 192.168.43.123
PORT = 9999 #open port 18000 for connection
s = socket.socket(AF_INET, SOCK_STREAM)
try:
s.bind((HOST, PORT))
except socket.error as e:
print("Bind error, Error code: ",e.strerror,"Message: ",e.strerror)
sys.exit(1)
print("Bind successful")
s.listen(10) #how many connections can it receive at one time
print("In the loop")
while True:
connect_device, addr = s.accept() # accept the connection
print("Connected by: ", addr)
#msg1 = 'Thank you for connecting' + "\r\n"
#connect_device.send(msg1.encode('ascii'))
data = connect_device.recv(4096) # how many bytes of data will the server receive
data = data.decode('ascii','ignore')
print("Received: ", repr(data))
conn = sqlite3.connect("ciao.db")
c=conn.cursor()
#string = "Hey tell me something about dengue"
#string2 = string.lower()
string = repr(data)
string2 = string.lower()
list_items = word_tokenize(string2)
list_items2 = []
for st in list_items:
list_items2.append(st.strip())
print("List items = ",list_items2)
Greetings = ['hi', "hey"]
c.execute("SELECT Disease_Name FROM ciao")
data = c.fetchall()
data2 = []
for i in data:
for j in i:
if j is not None:
data2.append(j)
print("data2 = ",data2)
msg = ""
print("loop starts")
for i in list_items2:
print(i)
print("Data = ",data2)
if i in data2:
if 'symptoms' in list_items2:
c.execute("SELECT Symptoms from ciao WHERE Disease_Name = (?)",(i,))
sym = c.fetchall()
for j in sym:
for k in j:
msg += k + " "
if 'remedial' in list_items2:
c.execute("SELECT Remedial_Measures from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'medicines' in list_items2:
c.execute("SELECT Medicines from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'diagnostic' in list_items2:
c.execute("SELECT Diagnostic_tests from ciao WHERE Disease_Name = (?)", (i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if 'hospitals' in list_items2:
c.execute("SELECT Related_Hospitals from ciao WHERE Disease_Name = (?)",(i,))
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
if not('symptoms' in list_items2) and not('remedial' in list_items2) and not('medicines' in list_items2) and not('diagnostic' in list_items2) and not('hospitals' in list_items2):
c.execute("SELECT * from ciao WHERE Disease_Name = (?)",(i,) )
rem = c.fetchall()
for j in rem:
for k in j:
msg += k + " "
else:
if i in Greetings:
if len(list_items) == 1 or len(list_items) == 0:
msg = "Hello I am Pi"
if msg == "":
msg = "Sorry"
print(msg)
connect_device.sendall(msg.encode('ascii'))
#connect_device.send(msg.encode('utf-8'))
conn.close()
connect_device.close()
s.close()