我一直在尝试在Android Studio上创建一个客户端项目,该项目将连接到我在Python(Pycharm)中创建的服务器。至于使用的IP,我在服务器上输入了本地主机,在客户端输入了计算机服务器的IPV4。 调试是通过手机本身而不是模拟器进行的。
当我尝试运行代码并使用相同的端口通过ipv4连接到服务器时,我的连接超时了。 此时,调试器在尝试从服务器获取消息时卡在客户端类上 - “while((bytesRead = inputStream.read(buffer))” - 在服务器上行时,代码未收到来自客户的任何消息,因此它一直停留在接收上。
如何解决此问题?
客户端代码: - 发生连接的地方
public class RequestAndAnswer extends AsyncTask<Void, Void, Void> {
private String dstAddress,result1;
private int dstPort;
private String response = "";
private String out;
RequestAndAnswer(String output)
{
dstAddress = "1.5.0.66"; //fake ipv4
out= output;
dstPort= 8886;
}
@Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
//send out to server
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF(out);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
主要代码:
public void onClick(View v)
{
if(v == loginButton)
{
String userNameString = userName.getText().toString();
String passwordString = password.getText().toString();
String output ="100"+
intToString(userNameString.length())
+userNameString
+ intToString(passwordString.length())
+passwordString;
RequestAndAnswer myClient = new RequestAndAnswer(output);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
myClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClient.execute();
String answer="";
do {
answer = myClient.getResult(); /**In order to make sure that I
will get my response after the
communication started between
the server and the client **/
}
while(answer.matches(""));
if(answer.matches("1100"))
{
Intent i = new Intent(this,Computer_choosing_selection_activity.class);
i.putExtra("username",userNameString);
startActivity(i);
finish();
}
else if(answer.matches("1101"))
{
String error = "The username and password do not match";
errorText.setTextColor(Color.RED);
errorText.setText(error);
}
else
{
String error = "Could not connect";
errorText.setTextColor(Color.RED);
errorText.setText(error);
}
}
AndroidManifest.XML包含以下几行 -
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
服务器代码: - 在python中
import socket
import sys
HOST = '127.0.0.1' # Symbolic name, meaning all available interfaces
PORT = 8886 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
data = s.recv(1024)
number = data.substr(0,3)
if(number == "100"):
data = data[4:]
len=data[0:3]
data=data[2:]
name = data[:int(len)]
data = data[int(len):]
len=data[0:3]
data=data[2:]
password = data[:int(len)]
if((name == "Tod") and (password == "Aa123456")):
conn.send("1100")
else:
conn.send("1101")
s.close()
编辑: 我在服务器中将地址更改为IPV4而不是本地127.0.0.1并且我设法连接虽然它之前给了我以下错误
“Socket.error:[Errno 10057]请求发送或接收数据被拒绝,因为该组件未连接到套接字并提供了一个地址(通过调用sendto发送数据套接字单元时)”
在此消息之后,我得到一个“已连接”的输出,程序关闭。