gpt4 book ai didi

android - 如何解决 客户端未连接或不再连接。你在 login() 之前调用了 connect() 吗?

转载 作者:行者123 更新时间:2023-12-04 10:13:04 26 4
gpt4 key购买 nike

我正在使用托管在 aws 控制台中的 prosody xmpp 服务器,我正在尝试使用我的凭据进行连接以登录,但每次遇到相同的错误时。我是为此目的而使用的。我搜索了所有 git 和 stackovrflow,但找不到一个

我的主要 Activity .java

private boolean register(final String paramString1,final String paramString2) {
try {
XMPP.getInstance().register(paramString1, paramString2);
return true;

} catch (XMPPException localXMPPException) {
localXMPPException.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
return false;
}

private boolean login(final String user,final String pass,final String username) {
try {
XMPP.getInstance().login(user, pass, username);
sendBroadcast(new Intent("liveapp.loggedin"));
return true;
} catch (Exception e) {
e.printStackTrace();
try {
XMPP.getInstance().login(user, pass, username);
sendBroadcast(new Intent("liveapp.loggedin"));

return true;
} catch (XMPPException e1) {
e1.printStackTrace();
} catch (SmackException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}catch (Exception e1){
e1.printStackTrace();
}
}
return false;
}

public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

public UserLoginTask() {
}

protected Boolean doInBackground(Void... paramVarArgs) {
String mEmail = "abc";
String mUsername = "abc";
String mPassword = "welcome";

if (register(mEmail, mPassword)) {
try {
XMPP.getInstance().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return login(mEmail, mPassword, mUsername);

}

protected void onCancelled() {
mAuthTask = null;

}

@Override
protected void onPreExecute() {
super.onPreExecute();

}

protected void onPostExecute(Boolean success) {
mAuthTask = null;
try {
if (success) {

messageListener = new ChatMessageListener() {
@Override
public void processMessage(Chat chat, Message message) {

// here you will get only connected user by you

}
};


packetListener = new StanzaListener() {
@Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {

if (packet instanceof Message) {
final Message message = (Message) packet;

// here you will get all messages send by anybody
}
}
};

chatListener = new ChatManagerListener() {

@Override
public void chatCreated(Chat chatCreated, boolean local) {
}
};


try {
String opt_jidStr = "abc";

try {
opt_jid = JidCreate.bareFrom(Localpart.from(opt_jidStr), Domainpart.from(HOST));
} catch (XmppStringprepException e) {
e.printStackTrace();
}
String addr1 = XMPP.getInstance().getUserLocalPart(getApplicationContext());
String addr2 = opt_jid.toString();
if (addr1.compareTo(addr2) > 0) {
String addr3 = addr2;
addr2 = addr1;
addr1 = addr3;
}
chat = XMPP.getInstance().getThreadChat(getApplicationContext(), addr1, addr2);
if (chat == null) {
chat = XMPP.getInstance().createChat(getApplicationContext(), (EntityJid) opt_jid, addr1, addr2, messageListener);
Log.e(TAG, "chat value single chat 1 :" + chat);
} else {
chat.addMessageListener(messageListener);
Log.e(TAG, "chat value single chat 2:" + chat);
}

} catch (Exception e) {
e.printStackTrace();
}


XMPP.getInstance().addStanzaListener(getApplicationContext(), packetListener);
XMPP.getInstance().addChatListener(getApplicationContext(), chatListener);
XMPP.getInstance().getSrvDeliveryManager(getApplicationContext());

} else {

}
} catch (Exception e) {
e.printStackTrace();
}

}
}

private void attemptLogin() {
if (mAuthTask != null) {
return;
}

boolean cancel = false;
View focusView = null;

if (cancel) {
focusView.requestFocus();
} else {
try {
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
} catch (Exception e) {

}

}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
databaseReference = FirebaseDatabase.getInstance().getReference().child("UserInfo");

attemptLogin();
}

}

XMPP.java 文件
private XMPPTCPConnectionConfiguration buildConfiguration() throws XmppStringprepException {
XMPPTCPConnectionConfiguration.Builder builder =
XMPPTCPConnectionConfiguration.builder();

builder.setHost(HOST);
builder.setPort(PORT);
builder.setCompressionEnabled(false);
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setSendPresence(true);
DomainBareJid serviceName = JidCreate.domainBareFrom(HOST);
builder.setServiceName(serviceName);

return builder.build();
}

private XMPPTCPConnection getConnection() throws XMPPException, SmackException, IOException, InterruptedException {
Log.e(TAG, "Getting XMPP Connect");
if (isConnected()) {
Log.e(TAG, "Returning already existing connection");
return this.connection;
}

long l = System.currentTimeMillis();
try {
if(this.connection != null){
Log.e(TAG, "Connection found, trying to connect");
this.connection.connect();
}else{
Log.e(TAG, "No Connection found, trying to create a new connection");
XMPPTCPConnectionConfiguration config = buildConfiguration();
SmackConfiguration.DEBUG = true;
this.connection = new XMPPTCPConnection(config);
this.connection.connect();
}
} catch (Exception e) {
Log.e(TAG,"some issue with getting connection :" + e.getMessage());

}

Log.e(TAG, "Connection Properties: " + connection.getHost());
Log.e(TAG, "Time taken in first time connect: " + (System.currentTimeMillis() - l));
return this.connection;
}

public static XMPP getInstance() {
if (instance == null) {
synchronized (XMPP.class) {
if (instance == null) {
instance = new XMPP();
}
}
}
return instance;
}

public void close() {
Log.e(TAG, "Inside XMPP close method");
if (this.connection != null) {
this.connection.disconnect();
}
}

private XMPPTCPConnection connectAndLogin(Context context) {
Log.e(TAG, "Inside connect and Login");
if (!isConnected()) {
Log.e(TAG, "Connection not connected, trying to login and connect");
try {
String username = "user1";
String password = "qwerty123";
this.connection = getConnection();
Log.e(TAG, "XMPP username :" + username);
Log.e(TAG, "XMPP password :" + password);
this.connection.login(username, password);
Log.e(TAG, "Connect and Login method, Login successful");
context.sendBroadcast(new Intent(ACTION_LOGGED_IN));
} catch (XMPPException localXMPPException) {
Log.e(TAG, "Error in Connect and Login Method1");
localXMPPException.printStackTrace();
} catch (SmackException e) {
Log.e(TAG, "Error in Connect and Login Method2");
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "Error in Connect and Login Method3");
e.printStackTrace();
} catch (InterruptedException e) {
Log.e(TAG, "Error in Connect and Login Method4");
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.e(TAG, "Error in Connect and Login Method5");
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error in Connect and Login Method6");
e.printStackTrace();
}
}
Log.e(TAG, "Inside getConnection - Returning connection");
return this.connection;
}

public boolean isConnected() {
return (this.connection != null) && (this.connection.isConnected());
}

public EntityFullJid getUser() {
if (isConnected()) {
return connection.getUser();
} else {
return null;
}
}

public void login(String user, String pass, String username)
throws XMPPException, SmackException, IOException, InterruptedException, XMPPException {
Log.e(TAG, "inside XMPP getlogin Method");
long l = System.currentTimeMillis();
XMPPTCPConnection connect = getConnection();
if (connect.isAuthenticated()) {
Log.e(TAG, "User already logged in");
return;
}

Log.e(TAG, "Time taken to connect: " + (System.currentTimeMillis() - l));

l = System.currentTimeMillis();
try{
connect.login(user, pass);
}catch (Exception e){
Log.e(TAG, "Issue in login, check the stacktrace");
Log.e(TAG, e.getMessage());
e.printStackTrace();
}

Log.e(TAG, "Time taken to login: " + (System.currentTimeMillis() - l));

Log.e(TAG, "login step passed");

PingManager pingManager = PingManager.getInstanceFor(connect);
pingManager.setPingInterval(10000);

}

public void register(String user, String pass) throws XMPPException, SmackException.NoResponseException, SmackException.NotConnectedException {
Log.e(TAG, "inside XMPP register method, " + user + " : " + pass);
long l = System.currentTimeMillis();
try {
AccountManager accountManager = AccountManager.getInstance(getConnection());
accountManager.sensitiveOperationOverInsecureConnection(true);
accountManager.createAccount(Localpart.from(user), pass);
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
Log.e(TAG, "Time taken to register: " + (System.currentTimeMillis() - l));
}


public String getUserLocalPart(Context context){
return connectAndLogin(context).getUser().getLocalpart().toString();
}

public EntityFullJid getUser(Context context){
return connectAndLogin(context).getUser();
}

}

我得到的错误
    E/XMPP-EXAMPLE: Client is not, or no longer, connected. Did you call connect() before login()?
org.jivesoftware.smack.SmackException$NotConnectedException: Client is not, or no longer, connected. Did you call connect() before login()?

at org.jivesoftware.smack.AbstractXMPPConnection.throwNotConnectedExceptionIfAppropriate(AbstractXMPPConnection.java:667) at org.jivesoftware.smack.AbstractXMPPConnection.login(AbstractXMPPConnection.java:512)
at org.jivesoftware.smack.AbstractXMPPConnection.login(AbstractXMPPConnection.java:491)
at xmpp.XMPP.connectAndLogin(XMPP.java:120)
at xmpp.XMPP.removeChatListener(XMPP.java:226)
at SplashScreenActivity.onDestroy(SplashScreenActivity.java:255)
at android.app.Activity.performDestroy(Activity.java:7068)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1154)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4280)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4311)
at android.app.ActivityThread.-wrap6(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1586)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

最佳答案

消息很明确,您在建立实际连接之前正在调用连接的 login(...)。这可能是由于在调用 login 之前连接时立即丢失连接造成的。因为你只是把你的代码扔给我们而不是做一个最小的例子,我无法理解。此外,我很久以前就停止使用异步任务,这使得它更难以遵循。这是使用 MVVM 和 Coroutine 制作的示例

class ChatsViewModel(val app: Application) : AndroidViewModel(app) {

private val chatApp: App = app as App

fun getConnection(): XMPPTCPConnection? {
return chatApp.xmppConnection
}

fun login(username: String, password: String) = viewModelScope.launch(Dispatchers.IO) {
if(chatApp.xmppConnection !=null && chatApp.xmppConnection!!.isAuthenticated) return@launch

val config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setHostAddress(InetAddress.getByName("192.168.1.102"))
.setXmppDomain(JidCreate.domainBareFrom(Constants.JABBER_DOMAIN))
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.enableDefaultDebugger()
.build()

val conn = XMPPTCPConnection(config)
try {
conn.connect()
} catch (e: Exception) {
//conn failed
}
if (!conn.isConnected) {
//alert use is not connected
}else{
try {
conn.login()
} catch (e: Exception) {
//failed to login
}

if (!conn.isAuthenticated) {
//alert user he is not logged in
}
else {
chatApp.xmppConnection = conn

//do your thing here. As example we are
//going to send presence stanza
val presence = Presence(Presence.Type.available)
presence.status = "Gone fishing"
try {
getConnection()?.sendStanza(presence)
} catch (e: Exception) {
//sending failed
}

这是您将如何在 fragment (或 Activity )中使用该 View 模型的方法
class ChatsFragment : Fragment() {

private lateinit var chatsViewModel: ChatsViewModel

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
chatsViewModel = ViewModelProvider(requireActivity()).get(ChatsViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_chats, container, false)
return root
}

override fun onResume() {
super.onResume()
chatsViewModel.login("xmpp_id_local_part", "123456")
}

override fun onStop() {
super.onStop()
chatsViewModel.logout()
}
}
}
}
}
}

关于android - 如何解决 客户端未连接或不再连接。你在 login() 之前调用了 connect() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61231098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com