smack cannot retrieve offline messages via OfflineMessageManager - java

I have a problem with while getting offline messages from ejabberd server 18.01 via smack library.
I have a connector method
private static AbstractXMPPConnection connectToServer(String serverHost, Integer port, String userName, String userPassword) {
DomainBareJid xmppDomain = null;
try {
xmppDomain = JidCreate.domainBareFrom(serverHost);
} catch (XmppStringprepException e) {
System.out.println("XMPP Domain initialization exception " + e.getMessage());
return null;
}
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(xmppDomain)
.setHost(serverHost)
.setPort(port)
.setDebuggerEnabled(true)
.setSendPresence(false)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect().login(userName, userPassword);
return connection;
} catch (XMPPException | SmackException | IOException | InterruptedException e) {
System.out.println("Something went wrong while connection to server: " + e.getMessage());
connection.disconnect();
return null;
}
}
and offline messages receiver
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval()) {
offlineMessageManager.getMessages()
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
// offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
I start running message listener at the background. I see that database has an offline message and in the dubug node I see that offlineMessageManager.getMessageCount() returns the proper number of offline messages but method offlineMessageManager.getMessages() returns noting. The smack version is 4.2.3 but earlier version has the same problem
UPDATED
I found a workaround because it doesn't look like a obvious solution
public class ListenMessagesFromServerCommand implements Runnable {
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval() && offlineMessageManager.getMessageCount() > 0) {
List<String> messagesNodes = offlineMessageManager.getHeaders().stream()
.map(OfflineMessageHeader::getStamp)
.collect(Collectors.toList());
offlineMessageManager.getMessages(messagesNodes)
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException | InterruptedException e) {
System.out.println("Error sending presence available type " + e.getMessage());
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
}

Related

How to handle timeout exception - Smbj

I'm just getting started with java development. My ex-colleagues write a code(Code 1). I recently faced the timeout exception.
Code 1:
public String deleteFiles(String DOMAIN0, String USER, String PASSWORD, String SRC_DIR, String DST_DIR, String ext, String ipAddress, String dstRoot) {
SmbConfig config = SmbConfig.builder()
.withMultiProtocolNegotiate(true)
.withSigningRequired(true)
.withDfsEnabled(true)
.build();
SMBClient client = new SMBClient(config);
try {
Connection connection = client.connect(ipAddress);
AuthenticationContext ac1 = new AuthenticationContext(USER, PASSWORD.toCharArray(), DOMAIN);
Session session1 = connection1.authenticate(ac1);
DiskShare share1 = (DiskShare) session1.connectShare(SRC_DIR);
if (DST_DIR.contains(".")) {
if (fileCheckExists) {
share1.rm(DST_DIR);
else {
boolean fileCheckExists = share1.folderExists(DST_DIR);
if (fileCheckExists) {
share1.rmdir(DST_DIR0, true);
catch (TimeoutException et) {
return "Error:" + et.getMessage();
catch (Exception ex) {
return "Error:" + ex.getMessage();
return "Completed";
}
I added a TimeoutException catch block, but eclipse show the error message(Unreachable catch block for TimeoutException. This exception is never thrown from the try statement body).
catch (TimeoutException et) {
return "Error:" + et.getMessage();
}
how to handle the timeout exception. Please suggust me.

JAVA Telegram bots api Error getting updates: Conflict: terminated by other long poll or webhook

I am using JAVA Telegram Bot API with Spring framework , I had a method in my HomeController and i had a class that handle all of the incoming messages from users. I got these errors in my spring log,then i got duplicated response from telegram bot API .whats is the problem ?
#PostConstruct
public void initBots() {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
BotService botService = new BotService();
try {
botsApi.registerBot(botService);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
[abrsystem1_bot Telegram Connection] org.telegram.telegrambots.logging.BotLogger.severe
BOTSESSION
org.telegram.telegrambots.exceptions.TelegramApiRequestException:
Error getting updates: [409] Conflict: terminated by other long poll
or webhook at
org.telegram.telegrambots.api.methods.updates.GetUpdates.deserializeResponse(GetUpdates.java:119)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.getUpdatesFromServer(DefaultBotSession.java:255)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.run(DefaultBotSession.java:186)
#Override
public void onUpdateReceived(Update update) {
try {
if (update.hasMessage() && update.getMessage().hasText()) {
String message_text = update.getMessage().getText();
String wellcome_text = "برای ثبت نام در سایت شماره تلفن همراه خود را به اشتراک بگذارید";
long chat_id = update.getMessage().getChatId();
if (message_text.equals("/start")) {
try {
SendMessage message = new SendMessage()
.setChatId(chat_id)
.setText(wellcome_text);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
List<KeyboardRow> keyboard = new ArrayList<KeyboardRow>();
KeyboardRow row = new KeyboardRow();
row.add((new KeyboardButton().setText("اشتراک شماره موبایل").setRequestContact(true)));
keyboard.add(row);
keyboardMarkup.setKeyboard(keyboard);
message.setReplyMarkup(keyboardMarkup);
try {
execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (message_text.equals("تایید مشخصات کاربری")) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chat_id).setText("اطلاعات مورد تایید قرار گرفت");
try {
execute(sendMessage);
removeMarker(chat_id);
showContactInfo(chat_id, update);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (message_text.equals("تغییر مشخصات")) {
} else {
showUnknownCommand(chat_id);
}
} else if (update.getMessage().getContact() != null && update.getMessage().getChat() != null) {
long chat_id = update.getMessage().getChatId();
showContactInfo(chat_id, update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I finally solved my problem after a day!when i was debugging my project with intellij idea on my computer , i created many instances for debug so i got multiple response from same chat id in telegram bot.so boring problem....

How to use UserSearchManager to check user has registered or not in xmpp?

I have started to develop chat application. I needed to check user has registered or not in xmpp server.So when user trying to register,I want check user has already registered or not in xmpp server. After xmpp server connected successfully,Tried to search as number using Usersearchmanager.But Getting error as
java.lang.IllegalArgumentException: Must have a local(user) JID set.Either you didn 't configure one or you where not connected at least once
at org.jivesoftware.smack.filter.IQReplyFilter. < init > (IQReplyFilter.java: 94)
at org.jivesoftware.smack.AbstractXMPPConnection.createPacketCollectorAndSend(AbstractXMPPConnection.java: 699)
at org.jivesoftware.smackx.search.UserSearch.getSearchForm(UserSearch.java: 73)
at org.jivesoftware.smackx.search.UserSearchManager.getSearchForm(UserSearchManager.java: 71)
at com.techno.samplechat.Myxmpp.searchUsers(Myxmpp.java: 335)
at com.techno.samplechat.Myxmpp$XMPPConnectionListener.connected(Myxmpp.java: 284)
at org.jivesoftware.smack.AbstractXMPPConnection.callConnectionConnectedListener(AbstractXMPPConnection.java: 1162)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java: 850)
at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java: 365)
at com.techno.samplechat.Myxmpp$1.run(Myxmpp.java: 117)
at java.lang.Thread.run(Thread.java: 818)
Code:
private void CreateAccount() {
org.jivesoftware.smackx.iqregister.AccountManager am = org.jivesoftware.smackx.iqregister.AccountManager
.getInstance(connection);
am.sensitiveOperationOverInsecureConnection(true);
Map < String, String > attributes = new HashMap < String, String > ();
attributes.put("username", loginUser);
attributes.put("email", "Manikandan.s#technoduce.com");
attributes.put("password", passwordUser);
attributes.put("name", UserName);
try {
if (am.supportsAccountCreation()) {
am.createAccount(
loginUser,
passwordUser,
attributes);
login();
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
private void login() {
try {
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ChatManager.getInstanceFor(connection).addChatListener(this);
}
#
Override
public void chatCreated(Chat chat, boolean createdLocally) {
Log.i("service", "chatCreated()");
System.out.println("+chatList++" + chat.getParticipant());
chat.addMessageListener(this);
}
#
Override
public void entriesAdded(Collection < String > addresses) {
}
#
Override
public void entriesUpdated(Collection < String > addresses) {
}
#
Override
public void entriesDeleted(Collection < String > addresses) {
}
#
Override
public void presenceChanged(Presence presence) {
}
#
Override
public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat || message.getType() == Message.Type.normal) {
if (message.getBody() != null) {
// Toast.makeText(this,message.getFrom() + " : " + message.getBody(),Toast.LENGTH_LONG).show();
System.out.println("++From++" + message.getFrom() + "++Body++" + message.getBody());
}
}
}
#
Override
public void pingFailed() {
}
private class XMPPConnectionListener implements ConnectionListener {
#
Override
public void connected(XMPPConnection connection) {
Log.e("success", "Connected");
try {
searchUsers(loginUser);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
// CreateAccount();
}
#
Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
#
Override
public void connectionClosed() {
}
#
Override
public void connectionClosedOnError(Exception e) {
System.out.println("+_" + e.toString());
}
#
Override
public void reconnectionSuccessful() {
}
#
Override
public void reconnectingIn(int seconds) {
}
#
Override
public void reconnectionFailed(Exception e) {
}
}
public void searchUsers(String userName) throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
UserSearchManager search = new UserSearchManager(connection);
Form searchForm = search
.getSearchForm("search." + connection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = search
.getSearchResults(answerForm, "search." + connection.getServiceName());
if (data.getRows() != null) {
for (ReportedData.Row row: data.getRows()) {
for (String value: row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
} else {
CreateAccount();
}
}
String you are looking for must to be a JID, not an username:
you need something like:
user1#myserver
and not just
user1
Then, it's quite useless in your usecase to check for JID.
I have register user using below code on smack 4.1:-
//Login User
public XMPPTCPConnection loginUser(Context objContext, XMPPTCPConnection objXmpptcpConnection, String strUsername, String strPassword) {
try {
AccountManager objAccountManager = AccountManager.getInstance(objXmpptcpConnection);
objAccountManager.createAccount(strUsername, strPassword);
objXmpptcpConnection = loginToServer(objXmpptcpConnection, strUsername, strPassword);
} catch (SmackException | XMPPException e) {
System.out.println("Msg=" + e.getMessage() + "\nCause =" + e.getCause() + "\n Local msg=" + e.getLocalizedMessage() + "\n stack=" + e.getStackTrace() + "\n class " + e.getClass());
System.out.println("Code=" + e.getStackTrace()[0].getLineNumber());
if (e.getMessage().contains("conflict")) {
objXmpptcpConnection = loginToServer(objXmpptcpConnection, strUsername, strPassword);
}
}
return objXmpptcpConnection;
}
private XMPPTCPConnection loginToServer(XMPPTCPConnection objXmpptcpConnection, String strUsername, String strPassword) {
try {
objXmpptcpConnection.login(strUsername + "#" + AppConstants.HOST, strPassword, "example");
// objXmpptcpConnection.sendPacket(new Presence(Presence.Type.unavailable));
//objXmpptcpConnection.sendPacket(new Presence(Presence.Type.available));
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("XMPPChatDemoActivity", "Logged in as "
+ objXmpptcpConnection.getUser());
Toast.makeText(
objContext,
"log in as "
+ objXmpptcpConnection.getUser(),
Toast.LENGTH_SHORT).show();
return objXmpptcpConnection;
}
Using above two methods register user to ejabberd successfully.
And Connect Method is:-
public XMPPTCPConnection connect(String strUsername, String strPassword) throws IOException, XMPPException, SmackException {
objXmpptcpConnection = null;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Create a connection
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(Constants.HOST);
config.setPort(Constants.PORT);
config.setHost(Constants.HOST);
config.setDebuggerEnabled(true);
config.setSendPresence(true);
config.setUsernameAndPassword(strUsername + "#" + Constants.HOST, strPassword);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
objXmpptcpConnection = new XMPPTCPConnection(config.build());
objXmpptcpConnection.setUseStreamManagement(true);
objXmpptcpConnection.setUseStreamManagementResumption(true);
try {
ProviderManager objProviderManager = new ProviderManager();
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
// Offline Message Requests
objProviderManager.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
// Offline Message Indicator
objProviderManager.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
objXmpptcpConnection.connect();
System.out.println("Connected to===>" + objXmpptcpConnection.getHost());
objXmpptcpConnection.login();
objDeliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(objXmpptcpConnection);
objDeliveryReceiptManager.autoAddDeliveryReceiptRequests();
objDeliveryReceiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.disabled);
objDeliveryReceiptManager.addReceiptReceivedListener(this);
} catch (XMPPException e) {
e.printStackTrace();
return objXmpptcpConnection;
} catch (SmackException e) {
e.printStackTrace();
return objXmpptcpConnection;
} catch (IOException e) {
e.printStackTrace();
return objXmpptcpConnection;
}
return objXmpptcpConnection;
}
Also you want to check ejabberd side configuration also.
Its working for me tried using the answer :- Smack API User search.
Hope its useful to you.

Server closes after one client disconnect (JAVA)

My server closes after one clients disconnects,and I can write only one more message then it crashes.I wonder why,since I only close the client socket when it types "EXIT SERVER" .This is the exception it throws:
java.io.EOFException
This is my code :
import java.net.*;
import java.io.*;
public class ServerPeer extends Thread {
Socket _socket;
String username;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void sendMessage(String _username, String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public synchronized void run() {
try {
ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
String divide = _message.getAll().substring(0, _message.getAll().indexOf(":"));
username = divide;
Server.listofusers.add(username);
for (ServerPeer sp : Server.listofpeers) {
if (_message.getAll().contains("EXIT SERVER")) {
Server.listofpeers.remove(sp);
_socket.close();
}
if (_message instanceof PrivateMessage) {
PrivateMessage privm = (PrivateMessage) _message;
for (ServerPeer sp2 : Server.listofpeers) {
if (sp2.username.equals(privm.getReceiver())) {
sp2.sendMessage(divide, privm.getAll());
String priv = privm.getAll().replaceAll("/w", "");
System.out.println(priv);
break;
}
}
} else {
sp.sendMessage(divide, _message.getAll());
System.out.println(_message.getAll());
}
}
_ois = new ObjectInputStream(_socket.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Server Class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static ServerConfig _svconfig = new ServerConfig();
public static ArrayList<ServerPeer> listofpeers = new ArrayList<ServerPeer>();
public static ArrayList<String> listofusers = new ArrayList<String>();
public static int i = 0;
// final static int _mysocket;
public static void main(String[] args) {
try {
final int _mysocket = _svconfig.getPORTNumber();
System.out.println("Wainting for clients.....");
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
} catch (MissingKeyException e) {
e.printStackTrace();
} catch (UnknownKeyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (BindException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SocketException e) {
System.out.println("You have been disconnected");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT:
Exception thrown in the console of the client who disconnects:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2328)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2797)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at ClientPeer.serverEcho(ClientPeer.java:35)
at ClientPeer.run(ClientPeer.java:44)
BUILD STOPPED (total time: 1 minute 26 seconds)
From what I can tell i'd guess your code is incorrect, but it hard to tell without more code.
At first glance it seems that if too many people connect to your server you just shut down the entire server not just those connections.
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
A better approach would be something like the following. If too many users try to connect, just close the users connection.
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
boolean alive = true;
while (alive) {
try {
//Keep accepting connection request
Socket clientRequest = _serversocket.accept();
//Check if too many user are connected
if (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}else{
//Reject connection if too many connected
clientRequest.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
//When server dead close it down
_serversocket.close();
Hope this helps.
Your code must be exiting after the client thread is terminated, create a thread that has the server accept method that starts the client thread, something like this,
/**
*/
private class ServerListener extends Thread
{
/**
*/
public void run()
{
try
{
Socket clientSocket = socket.accept();
System.out.println("client connected => "+clientSocket.getInetAddress().getHostAddress());
ServerListener th = new ServerListener();
th.start();
ClientThread cth = new ClientThread(clientSocket);
cth.start();
clients.add(cth);
return;
}
catch (Exception e)
{
e.printStackTrace();
//Main.getInsatance().println(e);
//Main.getInstance().println("socket disconnected => "+clientSocket.getInetAddress().getHostAddress());
}
}
}

Reading and Writing to Sockets, Java

I have a little problem with reading and writing to Sockets in my Server/Client Java application. Server have connection to database. I want to send an object "Employee" consist User Data (Name, Surname, Password) to Server, then Server look up to database about this user and resend to Client information - positive (1) or negative (-1).
First, when I want to send an object Employee, I've got :
"java.net.SocketException: Software caused connection abort: socket write error"
I have my Firewall turned off.
Second, when I want to send and receive just int through writeInt - readInt method for test, I can't to read anything on Server.
What's the problem? Please help.
Code Server:
class ClientCommunication implements Runnable {
private Socket incoming;
public ClientCommunication(Socket clientSocket) {
incoming = clientSocket;
}
public void run() {
try {
synchronized (this) {
try {
serverObjectOutput = new ObjectOutputStream(
incoming.getOutputStream());
serverObjectInput = new ObjectInputStream(
incoming.getInputStream());
} finally {
incoming.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
synchronized(this) {
while (true) {
try{
int operation = serverObjectInput.readInt();
switch(operation) {
case 1:
Employee employee = (Employee) serverObjectInput.readObject();
String SelectUserDataSQL = "SELECT COUNT(*) AS COUNT FROM pracownik where Imie = ? AND Nazwisko = ? AND Haslo = ?";
PreparedStatement CheckEmployeeLogin;
CheckEmployeeLogin = conn.prepareStatement(SelectUserDataSQL);
CheckEmployeeLogin.setString(1, employee.getFirstName());
CheckEmployeeLogin.setString(2, employee.getLastName());
CheckEmployeeLogin.setString(3, new String(employee.getPassword()));
ResultSet resultSQL = CheckEmployeeLogin.executeQuery();
if (resultSQL.next())
if (resultSQL.getInt("COUNT") == 0)
serverObjectOutput.writeInt(1);
else serverObjectOutput.writeInt(-1);
break;
}
} catch(IOException | ClassNotFoundException | SQLException ex)
{
}
}
}
}
}
class ServerStart implements Runnable {
private int portNumber;
public ServerStart(int portNumber) {
this.portNumber = portNumber;
}
public void run() {
try {
conn = getConnection();
stat = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket incoming = serverSocket.accept();
clientSockets.add(incoming);
Runnable r = new ClientCommunication(incoming);
Thread t = new Thread(r);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Code Client:
public void actionPerformed(ActionEvent e) {
if (isConnected == false) {
String ServerIP = ip.getText().trim();
int ServerPort = Integer
.parseInt(port.getText().trim());
try {
ClientSocket = new Socket(ServerIP, ServerPort);
clientObjectInput = new ObjectInputStream(
ClientSocket.getInputStream());
clientObjectOutput = new ObjectOutputStream(
ClientSocket.getOutputStream());
isConnected = true;
} catch (IOException ex) {
}
synchronized (this) {
try {
ClientLoginFrame login = new ClientLoginFrame();
Employee employee = login.getEmployee();
clientObjectOutput.writeObject(employee);
int result = clientObjectInput.readInt();
if(result == 1)
{
// DO SOMETHING
}
else {
ClientSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
}
add an ex.printStackTrace() to see what is happening in your
catch(IOException | ClassNotFoundException | SQLException ex)
Server side, on your ClientCommunication class: it seems you are closing the socket before entering the while loop. So the socket is already closed and cannot send/receive messages. You should NOT call incoming.close() there, but at the end of your run() method.

Categories

Resources