I am implementing a Java Client-Server application for a university task and I'm stuck at the following point: I am obliged to use client-server and also update the view whenever the data in the database changes. What I have done is that whenever a change in the database should occur I notify all the clients with the "CHANGE IN DATA" message and then the client should read and understand this message in order to call a method that will update it's graphic interface. However, or I'm mistaking the reading part on client side or because of some error, the clients don't read the "CHANGE IN DATA" message so the whole gets stuck at this point and the view doesn't update.
Here are some relevant codes!
Server class:
public class FinesPaymentServer implements Runnable {
private Database database;
private UserGateway userGateway;
private FineGateway fineGateway;
private DriverGateway driverGateway;
private Socket connection;
private int ID;
static ArrayList<Socket> clientsConnected;
/**
* Constructor of the class connecting to the database and initializing the socket
* #param database the database used
* #param connection the socket for the server
* #param ID the id
*/
private FinesPaymentServer(Database database, UserGateway userGateway, FineGateway fineGateway, DriverGateway driverGateway, Socket connection, int ID) {
this.connection = connection;
this.userGateway = userGateway;
this.fineGateway = fineGateway;
this.driverGateway = driverGateway;
this.database = database;
this.ID = ID;
}
/**
* Run method of the threads for each socket on the server
*/
public void run() {
try {
while(true)
readFromClient(connection);
} catch (IOException | SQLException e) {
System.out.println(e);
}
}
/**
* Read method from the client
* #param client the client socket from where to read
* #throws IOException
* #throws SQLException
*/
public void readFromClient(Socket client) throws IOException, SQLException {
BufferedInputStream is = new BufferedInputStream(client.getInputStream());
InputStreamReader reader = new InputStreamReader(is);
StringBuffer process = new StringBuffer();
int character;
while((character = reader.read()) != 13) {
process.append((char)character);
}
System.out.println("[SERVER READ]: "+process);
String[] words = process.toString().split("\\s+");
switch (process.charAt(0)) {
case 'a' :
{
int type = database.verifyLogin(words[1], words[2]);
sendMessage(client, ""+type + " ");
break;
}
case 'b' :
{
String rs = userGateway.getUsers();
sendMessage(client, rs);
break;
}
case 'c' :
{
userGateway.createUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'd' :
{
userGateway.updateUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'e' :
{
userGateway.deleteUser(words[1]);
notifyClients();
break;
}
}
try {
Thread.sleep(1000);
} catch (Exception e){}
String time_stamp = new java.util.Date().toString();
String returnCode = "Single Socket Server responded at " + time_stamp + (char) 13;
sendMessage(client, returnCode);
}
/**
* Method for sending messages from the server to the client
* #param client the client socket where to send the message
* #param message the message itself to be sent
* #throws IOException
*/
private void sendMessage(Socket client, String message) throws IOException {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
System.out.println("[SERVER WRITE]: "+message);
writer.flush();
}
public void notifyClients() throws IOException
{
for(Socket s : clientsConnected)
{
sendMessage(s, "CHANGE IN DATA ");
}
}
/**
* #param args the command line arguments
* #throws java.sql.SQLException
*/
public static void main(String[] args) throws SQLException {
Database database = new Database();
UserGateway userGateway = new UserGateway();
FineGateway fineGateway = new FineGateway();
DriverGateway driverGateway = new DriverGateway();
clientsConnected = new ArrayList<>();
// Setting a default port number.
int portNumber = 2015;
int count = 0;
System.out.println("Starting the multiple socket server at port: " + portNumber);
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("Multiple Socket Server Initialized");
//Listen for clients
while(true) {
Socket client = serverSocket.accept();
clientsConnected.add(client);
Runnable runnable = new FinesPaymentServer(database, userGateway, fineGateway, driverGateway, client, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
} catch (Exception e) {}
}
}
The client class:
public class FinesPaymentClient implements Runnable {
private String hostname = "localhost";
private int port = 2015;
Socket socketClient;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor of the class
* #param hostname the host name of the connection
* #param port the port of the connection
* #throws UnknownHostException
* #throws IOException
*/
public FinesPaymentClient(String hostname, int port, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws UnknownHostException, IOException
{
this.hostname = hostname;
this.port = port;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
connect();
}
/**
* Method for connecting to the host by a socket
* #throws UnknownHostException
* #throws IOException
*/
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("Connection Established");
}
/**
* Method for reading response from the server
* #return the string read from the server
* #throws IOException
*/
public String readResponse() throws IOException {
String userInput;
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(socketClient.getInputStream()));
System.out.println("[CLIENT READ]:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
return userInput;
}
return userInput;
}
/**
* Method for closing connection between client and server
* #throws IOException
*/
public void closeConnection() throws IOException {
socketClient.close();
}
/**
* Method for writing messages to the server
* #param message the message to be sent
* #throws IOException
*/
public void writeMessage(String message) throws IOException {
String time_stamp = new java.util.Date().toString();
// Please note that we placed a char(13) at the end of process...
// we use this to let the server know we are at the end
// of the data we are sending
String process = message + (char) 13;
BufferedWriter stdOut = new BufferedWriter(
new OutputStreamWriter(socketClient.getOutputStream()));
stdOut.write(process);
System.out.println("[CLIENT WRITE]: "+process);
// We need to flush the buffer to ensure that the data will be written
// across the socket in a timely manner
stdOut.flush();
}
#Override
public void run() {
try {
String response;
while(true)
{
response = readResponse();
System.out.println("HERE"+response.substring(0, 13));
if(response.substring(0, 13).equals("CHANGE IN DATA"))
{
adminModel.setChange();
}
}
} catch (IOException e) {
System.out.println(e);
}
}
/**
* Main method of the application
* #param arg the parameters given as arguments
* #throws SQLException
* #throws UnknownHostException
* #throws IOException
*/
public static void main(String arg[]) throws SQLException, UnknownHostException, IOException {
AdministratorModel adminModel = new AdministratorModel();
PoliceModel policeModel = new PoliceModel();
PostModel postModel = new PostModel();
FinesPaymentClient client = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Runnable client2 = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Thread thread = new Thread(client2);
thread.start();
Login login = new Login();
ClientSide clientSide = new ClientSide(login, client, adminModel, policeModel, postModel);
}
}
ClientSide class:
public class ClientSide {
private final Login login;
private FinesPaymentClient client;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor instantiating needed classes
* #param login an instance of the login class
* #param client the client needing the control logic
* #param adminModel
* #param policeModel
* #param postModel
* #throws SQLException using classes connecting to a database sql exceptions can occur
*/
public ClientSide(Login login, FinesPaymentClient client, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws SQLException
{
this.login = login;
this.client = client;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
login.addButtonListener(new ButtonListener());
}
/**
* Listener for the login button. Reads, verifies and provides the interface according to logged in user type.
*/
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try
{
client.writeMessage("a " + login.field1.getText()+ " " + login.field2.getText());
String response = client.readResponse();
if(response.charAt(0) == '1')
{
login.setVisible(false);
AdministratorGUI administratorGUI = new AdministratorGUI(adminModel, client);
AdministratorController adminController = new AdministratorController(client, administratorGUI, adminModel);
}
//if user is post office employee
else if(response.charAt(0) == '2')
{
login.setVisible(false);
PostGUI postGUI = new PostGUI();
PostController postController = new PostController(client, postGUI, postModel);
}
//if user is police employee
else if(response.charAt(0) == '3')
{
login.setVisible(false);
PoliceGUI policeGUI = new PoliceGUI();
PoliceController policeController = new PoliceController(client, policeGUI, policeModel);
}
else
{
JOptionPane.showMessageDialog(null,"Login failed! Please try again!");
}
}
catch (IOException ex)
{
Logger.getLogger(ClientSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I'm 99% sure that the error is on client side reading the message sent from the server as notification, but I simply cannot figure it out how could I retrieve that message. Right now I have a try in the client threads run method, but doesn't work. Other classes and other functionalities work just fine, this is my only problem. Do you have any ideas what the mistake could be? I would appreciate any help.
Related
Good Day,
I am struggling with below error when trying to connect to IBM MQ. Unable to access createContext(); and forces me to use (JMSContext) cf.createConnection(); which is resulting me error as below:
"Exception in thread "main" java.lang.ClassCastException: com.ibm.mq.jms.MQConnection cannot be cast to javax.jms.JMSContext
at pushmsgs.main(pushmsgs.java:55)"
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.*;
public class pushmsgs {
// System exit status value (assume unset value to be 1)
private static int status = 1;
// Create variables for the connection to MQ
private static final String HOST = "22.188.133.100"; // Host name or IP address
private static final int PORT = 3415; // Listener port for your queue manager
private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
private static final String QMGR = "SITQUEUEMGR"; // Queue manager name
// private static final String APP_USER = "app"; // User name that application uses to connect to MQ
//private static final String APP_PASSWORD = "_APP_PASSWORD_"; // Password that the application uses to connect to MQ
private static final String QUEUE_NAME = "TESTQUEUE.MQAPP.REQ.RCV"; // Queue that the application uses to put and get messages to and from
/**
* Main method
*
* #param args
*/
public static void main(String[] args) {
// Variables
JMSContext context = null;
Destination destination = null;
JMSProducer producer = null;
JMSConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
// cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
//cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
// cf.setStringProperty(WMQConstants.USERID, APP_USER);
//cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
//cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");
// Create JMS objects
context = (JMSContext) cf.createConnection();
destination = context.createQueue("queue:///" + QUEUE_NAME);
long uniqueNumber = System.currentTimeMillis() % 1000;
TextMessage message = context.createTextMessage("Your lucky number today is " + uniqueNumber);
producer = context.createProducer();
producer.send(destination, message);
System.out.println("Sent message:\n" + message);
context.close();
recordSuccess();
} catch (JMSException jmsex) {
recordFailure(jmsex);
}
System.exit(status);
} // end main()
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* #param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
} else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
/**
* Process a JMSException and any associated inner exceptions.
*
* #param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}
}
Added JMS mvn dependency and com.ibm.mq.allclient dependency
It's because you are assigning the wrong object to the wrong variable.
context = (JMSContext) cf.createConnection();
I don't know why you would want to do that. A connection is not a context.
It should be:
Connection conn = cf.createConnection("MyUserId", "mypassword");
See my example called MQTestJMS51 here.
Using as an example a following code from https://www.jitendrazaa.com/blog/java/snmp/create-snmp-client-in-java-using-snmp4j/ to monitor a network when I send OIDs to an empty IP or to a device without SNMP the program throws an exception.
I use a for loop to read IPs. I have tried to change the flow of execution in different ways without success.
the program falls in the getAsStrint method with java.lang.NullPointerException
public class SNMPManager {
Snmp snmp = null;
String address = null;
/**
* Constructor
*
* #param add
*/
public SNMPManager(String add) {
address = add;
}
public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation
*/
for (int i = 37; i < 40; i++) {
System.out.println("ip x.x.x." + i);
SNMPManager client = new SNMPManager("udp:192.168.1." + i + "/161");
//SNMPManager client = new SNMPManager("udp:192.168.1.37/161");
client.start();
/**
* OID - .1.3.6.1.2.1.1.1.0 => SysDec
* OID - .1.3.6.1.2.1.1.5.0 => SysName
* => MIB explorer will be usefull here, as discussed in previous article
*/
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.5.0"));
System.out.println(".1.3.6.1.2.1.1.5.0" + " - SysName: " + sysDescr);
String sysDescr2 = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(".1.3.6.1.2.1.1.1.0" + " - SysDec: " + sysDescr2);
}
}
/**
* Start the Snmp session. If you forget the listen() method you will not
* get any answers because the communication is asynchronous
* and the listen() method listens for answers.
*
* #throws IOException
*/
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
// Do not forget this line!
transport.listen();
}
/**
* Method which takes a single OID and returns the response from the agent as a String.
*
* #param oid
* #return
* #throws IOException
*/
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[]{oid});
return event.getResponse().get(0).getVariable().toString();
}
/**
* This method is capable of handling multiple OIDs
*
* #param oids
* #return
* #throws IOException
*/
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if (event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
/**
* This method returns a Target, which contains information about
* where the data should be fetched and how.
*
* #return
*/
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}
make getAsString(OID oid) method like this
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[]{oid});
if(event.getResponse() != null){
return event.getResponse().get(0).getVariable().toString();
} else {
return "no target"
}
}
there are no target that is why null pointer exception
Im working on a simple ftp server, and the client must send multiples messages to the server, and for each message the server send back to the client a anwser. when the client sends one message it works perfectly and the server responds without any problem, for example, when the client sends "USER username" the server send back to the client "password needed".
But when the client sends another message "PASS password" (using the same socket) it doesnt work ! ONLY the first exchange works (for the username), when the first message is sent, the server anwser without any problem, but it block when it want to send the second message (for the password).
please anyone can help me ? thank you !!
here is my code :
#Test
public void testProcessPASS() throws IOException{
Socket socket = new Socket(server.getAddress(), server.getcmdPort());
this.ClientReceiveMessage(socket); // to flush
String cmd = "USER user_test\r\n";
this.ClientSendMessage(socket, cmd);
String anwser = this.ClientReceiveMessage(socket);
assertEquals("Response error.", Constants.MSG_331.replace("\r\n", ""), anwser);
//PROBLEME STARTS HERE :/
String cmd2 = "PASS pass_test\r\n";
this.ClientSendMessage(socket, cmd2);
String anwser2 = this.ClientReceiveMessage(socket);
assertEquals(Constants.MSG_230.replace("\r\n", ""), anwser2);
socket.close();
}
public void ClientSendMessage(Socket skt, String msg) throws IOException{
PrintWriter messageClient = new PrintWriter(new OutputStreamWriter(skt.getOutputStream()),true);
messageClient.println(msg);
messageClient.flush();
}
public String ClientReceiveMessage(Socket skt) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
String res = br.readLine() ;
return res;
}
this is the server code :
public class Server implements Runnable {
private ServerSocket cmdserverSocket;
private ServerSocket dataServerSocket;
private boolean running;
public Server() throws IOException {
this.cmdserverSocket = new ServerSocket(1024);
this.dataServerSocket = new ServerSocket(1025);
this.running = false;
}
public boolean isRunning() {
return this.running;
}
public InetAddress getAddress() {
return this.cmdserverSocket.getInetAddress();
}
public int getcmdPort() {
return this.cmdserverSocket.getLocalPort();
}
public int getDataPort() {
return this.dataServerSocket.getLocalPort();
}
public void run() {
// TODO Auto-generated method stub
this.running = true;
System.out.println("server started on port : " + this.getcmdPort());
while (this.running) {
try {
Socket socket = this.cmdserverSocket.accept();
new Thread(new FtpRequest(socket, this.dataServerSocket))
.start();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("server error : " + e.getMessage());
this.running = false;
}
}
}
}
and this is the class that handles client requests and that sends messages to client and running on a new thread :
public class FtpRequest implements Runnable {
private Socket cmdSocket;
private Socket dataSocket;
private BufferedReader cmdBufferedReader;
private DataOutputStream cmdDataOutputStream;
private ServerSocket dataServerSocket;
private boolean anonymous;
private boolean connected;
private String username;
private boolean processRunning;
private String directory;
public FtpRequest(Socket cmds, ServerSocket dts) throws IOException {
this.cmdSocket = cmds;
this.dataServerSocket = dts;
this.cmdBufferedReader = new BufferedReader(new InputStreamReader(
this.cmdSocket.getInputStream()));
this.cmdDataOutputStream = new DataOutputStream(
this.cmdSocket.getOutputStream());
this.anonymous = true;
this.connected = false;
this.username = Constants.ANONYMOUS_USER;
this.processRunning = true;
this.directory = "/home";
}
/**
* send a message on the socket of commands
*
* #param msg
* the msg to send on the socket of commands
* #throws IOException
*/
public void sendMessage(String msg) throws IOException {
System.out.println("FtpRequest sendMessage : " + msg);
PrintWriter messageClient = new PrintWriter(new OutputStreamWriter(
this.cmdDataOutputStream), true);
messageClient.println(msg);
messageClient.flush();
/*
* this.cmdDataOutputStream.writeBytes(msg);
* this.cmdDataOutputStream.flush(); this.cmdSocket.close();
*/
}
public void run() {
// TODO Auto-generated method stub
System.out.println("FtpRequest running ...");
try {
this.sendMessage(Constants.MSG_220); // service ready for new user
this.handleRequest();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // service ready for new user
}
/**
* this method handle the request readen from cmd socket and run the
* required method
*
* #throws IOException
*/
private void handleRequest() throws IOException {
String rqst = this.cmdBufferedReader.readLine();
Request request = new Request(rqst);
System.out.println("FtpRequest handleRequest" + rqst);
switch (request.getType()) {
case USER:
this.processUSER(request);
break;
case PASS:
this.processPASS(request);
break;
default:
this.sendMessage(Constants.MSG_502); // Command not implemented.\r\n
break;
}
/*
* if (this.processRunning = true) this.handleRequest();
*
* else { this.cmdSocket.close(); System.out.println("socket closed ");
* }
*/
}
private void processUSER(Request rqst) throws IOException {
System.out.println("FtpRequest processUSER");
if (rqst.getArgument().equals(Constants.ANONYMOUS_USER)) {
this.sendMessage(Constants.MSG_230); // user loged in
this.connected = true;
this.anonymous = true;
this.username = Constants.ANONYMOUS_USER;
} else if (rqst.getArgument().equals(Constants.USER_TEST)) {
this.sendMessage(Constants.MSG_331); // User name okay, need
// password.\r\n
this.username = Constants.USER_TEST;
} else
this.sendMessage(Constants.MSG_332);
}
private void processPASS(Request rqst) throws IOException {
System.out.println("FtpRequest processPASS");
if (rqst.getArgument().equals(Constants.USER_TEST)
&& rqst.getArgument().equals(Constants.PASS_TEST)) {
this.sendMessage(Constants.MSG_230);
this.connected = true;
this.anonymous = false;
} else
this.sendMessage(Constants.MSG_332); // au cas seulement le mot de
// passe est fourni
}
}
There are some problems with your code.
ClientSendMessage() is using PrintWriter.println(), which outputs a line break. But your input strings already have line breaks on them, so the println() is sending extra line breaks. Also, the line break println() outputs is platform-dependent, whereas FTP uses CRLF specifically. So you should not be using println() at all.
ClientReceiveMessage() does not account for multi-line responses. Per RFC 959, section 4.2 "FTP REPLIES":
A reply is defined to contain the 3-digit code, followed by Space
<SP>, followed by one line of text (where some maximum line length
has been specified), and terminated by the Telnet end-of-line
code. There will be cases however, where the text is longer than
a single line. In these cases the complete text must be bracketed
so the User-process knows when it may stop reading the reply (i.e.
stop processing input on the control connection) and go do other
things. This requires a special format on the first line to
indicate that more than one line is coming, and another on the
last line to designate it as the last. At least one of these must
contain the appropriate reply code to indicate the state of the
transaction. To satisfy all factions, it was decided that both
the first and last line codes should be the same.
Thus the format for multi-line replies is that the first line
will begin with the exact required reply code, followed
immediately by a Hyphen, "-" (also known as Minus), followed by
text. The last line will begin with the same code, followed
immediately by Space <SP>, optionally some text, and the Telnet
end-of-line code.
For example:
123-First line
Second line
234 A line beginning with numbers
123 The last line
The user-process then simply needs to search for the second
occurrence of the same reply code, followed by <SP> (Space), at
the beginning of a line, and ignore all intermediary lines. If
an intermediary line begins with a 3-digit number, the Server
must pad the front to avoid confusion.
The server's initial greeting is likely to be multi-line, but any response to any command can potentially be multi-line, so you need to handle that.
But more importantly, when doing error checking, you need to look at only the 3-digit response code, not the text that accompanies it. Except for a few select commands, like PASV, MLST/MLSD, etc, the text is otherwise arbitrary, the server can send whatever it wants. So you need to ignore the text except for those cases where it is actually needed, or when reporting error messages to the user.
Try something more like this:
private Socket socket;
private BufferedReader br;
#Test
public void testProcessPASS() throws IOException{
socket = new Socket(server.getAddress(), server.getcmdPort());
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.ClientReceiveMessage(220);
this.ClientSendMessage("USER user_test", 331);
this.ClientSendMessage("PASS pass_test", 230);
this.ClientSendMessage("QUIT", 221);
socket.close();
br = null;
socket = null;
}
public int ClientSendMessage(String msg, int ExpectedReplyCode) throws IOException{
Writer bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(msg);
bw.write("\r\n");
bw.flush();
return ClientReceiveMessage(ExpectedReplyCode);
}
public int ClientReceiveMessage(int ExpectedReplyCode) throws IOException{
String line = br.readLine();
String msgText = msgText.substring(4);
if ((line.length() >= 4) && (line[3] == '-')) {
String endStr = line.substring(0, 2) + " ";
do {
line = br.readLine();
msgText += ("\r\n" + line.substring(4));
}
while (line.substring(0, 3) != endStr);
}
int actualReplyCode = Integer.parseInt(line.substring(0, 2));
assertEquals("Response error. " + msgText, ExpectedReplyCode, actualReplyCode);
// TODO: if the caller wants the msgText for any reason,
// figure out a way to pass it back here...
return actualReplyCode;
}
The incoming data has to be fed back into the polling method and also should be processed further for another class.
public List<KAAMessage> fullPoll() throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
return pojoCol;
}
/**
* Converts a provided record-set to a {#link KpiMessage}.
*
* The following attributes are copied from record-set to pojo:
*
* <ul>
* <li>SEQ</li>
* <li>TABLENAME</li>
* <li>ENTRYTIME</li>
* <li>STATUS</li>
* </ul>
*
* #param rs
* the record-set to convert
* #return the converted pojo class object
* #throws SQLException
* if an sql error occurs during processing of recordset
*/
private KpiMessage convertRecordsetToPojo(ResultSet rs) throws SQLException {
KpiMessage msg = new KpiMessage();
int sequence = rs.getInt("SEQ");
msg.setSequence(sequence);
int action = rs.getInt("ACTION");
msg.setAction(action);
String tablename = rs.getString("TABLENAME");
msg.setTableName(tablename);
Timestamp entrytime = rs.getTimestamp("ENTRYTIME");
Date entryTime = new Date(entrytime.getTime());
msg.setEntryTime(entryTime);
Timestamp processingtime = rs.getTimestamp("PROCESSINGTIME");
if (processingtime != null) {
Date processingTime = new Date(processingtime.getTime());
msg.setProcessingTime(processingTime);
}
String keyInfo1 = rs.getString("KEYINFO1");
msg.setKeyInfo1(keyInfo1);
String keyInfo2 = rs.getString("KEYINFO2");
msg.setKeyInfo2(keyInfo2);
return msg;
}
This class has the Poll() method which reads message from the database. In the database I have SequeceID as unique number and it keeps on increasing for new data, but how can I get this new messages and feed it back to polling?
P.S: Please comment if you are down voting or closing my post because I am new here and I'd like to know the details.
this the Controller Class which runs the thread for the Poll() method.
public class RunnableController {
/** Here This Queue initializes the DB and have the collection of incoming message
*
*/
private static Collection<KaMessage> incomingQueue = new ArrayList<KAMessage>();
private Connection dbConncetion;
private ExecutorService threadExecutor;
private void initializeDb()
{
//catching exception must be adapted - generic type Exception prohibited
DBhandler con = new DBhandler();
try {
dbConncetion = con.initializeDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initialiseThreads()
{
try {
threadExecutor = Executors.newFixedThreadPool(10);
PollingSynchronizer read = new PollingSynchronizer(incomingQueue,
dbConncetion);
threadExecutor.submit(read);
}catch (Exception e){
e.printStackTrace();
}
}
private void shutDownThreads()
{
try {
threadExecutor.shutdown();
dbConncetion.close();
}catch (Exception e){
e.printStackTrace();
}
}
/** Here This Queue passes the messages and have the collection of outgoing message
*
*/
// private Collection<KpiMessage> outgingQueue = new ArrayList<KpiMessage>();
/**
* Main
*
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
System.out.println("Repetetive polling for each 6 seconds");
KpiProcessor kp = new KpiProcessor();
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is one of the most common application scenario that can be found all over the net. and I'm not asking any questions about the java codes that I did because I was successful in running it on my laptop where both the client and server part of the .java file resides. Rather I have had problem getting it to work in between two computers. I tried establishing physical connection using cross-over cable to connect two computers, and did a test to see if file transfers successfully and it did, however, keeping one Server part of the .java file in one computer and client part in the other, I tried to run the server first and then the client but it got a "access denied" error.
For reference here's my two .java files:
/* ChatClient.java */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClient {
private static int port = 5000; /* port to connect to */
private static String host = "localhost"; /* host to connect to (server's IP)*/
private static BufferedReader stdIn;
private static String nick;
/**
* Read in a nickname from stdin and attempt to authenticate with the
* server by sending a NICK command to #out. If the response from #in
* is not equal to "OK" go bacl and read a nickname again
*/
private static String getNick(BufferedReader in,
PrintWriter out) throws IOException {
System.out.print("Enter your nick: ");
String msg = stdIn.readLine();
out.println("NICK " + msg);
String serverResponse = in.readLine();
if ("SERVER: OK".equals(serverResponse)) return msg;
System.out.println(serverResponse);
return getNick(in, out);
}
public static void main (String[] args) throws IOException {
Socket server = null;
try {
server = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println(e);
System.exit(1);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
/* obtain an output stream to the server... */
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
/* ... and an input stream */
BufferedReader in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
nick = getNick(in, out);
/* create a thread to asyncronously read messages from the server */
ServerConn sc = new ServerConn(server);
Thread t = new Thread(sc);
t.start();
String msg;
/* loop reading messages from stdin and sending them to the server */
while ((msg = stdIn.readLine()) != null) {
out.println(msg);
}
}
}
class ServerConn implements Runnable {
private BufferedReader in = null;
public ServerConn(Socket server) throws IOException {
/* obtain an input stream from the server */
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
}
public void run() {
String msg;
try {
/* loop reading messages from the server and show them
* on stdout */
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
and here's the ChatServer.java:
/* ChatServer.java */
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Hashtable;
public class ChatServer {
private static int port = 5000; /* port to listen on */
public static void main (String[] args) throws IOException
{
ServerSocket server = null;
try {
server = new ServerSocket(port); /* start listening on the port */
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
}
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ChatServerProtocol {
private String nick;
private ClientConn conn;
/* a hash table from user nicks to the corresponding connections */
private static Hashtable<String, ClientConn> nicks =
new Hashtable<String, ClientConn>();
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_SPECIFY_NICK = "SPECIFY NICK";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
/**
* Adds a nick to the hash table
* returns false if the nick is already in the table, true otherwise
*/
private static boolean add_nick(String nick, ClientConn c) {
if (nicks.containsKey(nick)) {
return false;
} else {
nicks.put(nick, c);
return true;
}
}
public ChatServerProtocol(ClientConn c) {
nick = null;
conn = c;
}
private void log(String msg) {
System.err.println(msg);
}
public boolean isAuthenticated() {
return ! (nick == null);
}
/**
* Implements the authentication protocol.
* This consists of checking that the message starts with the NICK command
* and that the nick following it is not already in use.
* returns:
* msg_OK if authenticated
* msg_NICK_IN_USE if the specified nick is already in use
* msg_SPECIFY_NICK if the message does not start with the NICK command
*/
private String authenticate(String msg) {
if(msg.startsWith("NICK")) {
String tryNick = msg.substring(5);
if(add_nick(tryNick, this.conn)) {
log("Nick " + tryNick + " joined.");
this.nick = tryNick;
return msg_OK;
} else {
return msg_NICK_IN_USE;
}
} else {
return msg_SPECIFY_NICK;
}
}
/**
* Send a message to another user.
* #recepient contains the recepient's nick
* #msg contains the message to send
* return true if the nick is registered in the hash, false otherwise
*/
private boolean sendMsg(String recipient, String msg) {
if (nicks.containsKey(recipient)) {
ClientConn c = nicks.get(recipient);
c.sendMsg(nick + ": " + msg);
return true;
} else {
return false;
}
}
/**
* Process a message coming from the client
*/
public String process(String msg) {
if (!isAuthenticated())
return authenticate(msg);
String[] msg_parts = msg.split(" ", 3);
String msg_type = msg_parts[0];
if(msg_type.equals("MSG")) {
if(msg_parts.length < 3) return msg_INVALID;
if(sendMsg(msg_parts[1], msg_parts[2])) return msg_OK;
else return msg_SEND_FAILED;
} else {
return msg_INVALID;
}
}
}
class ClientConn implements Runnable {
private Socket client;
private BufferedReader in = null;
private PrintWriter out = null;
ClientConn(Socket client) {
this.client = client;
try {
/* obtain an input stream to this client ... */
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
/* ... and an output stream to the same client */
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.err.println(e);
return;
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
/* loop reading lines from the client which are processed
* according to our protocol and the resulting response is
* sent back to the client */
while ((msg = in.readLine()) != null) {
response = protocol.process(msg);
out.println("SERVER: " + response);
}
} catch (IOException e) {
System.err.println(e);
}
}
public void sendMsg(String msg) {
out.println(msg);
}
}
Now, what should I do in order to run this two files from two computers given that I have the physical connection(TCP/IP) setup already??
Thanks in advance... :)
Sounds like it's quite possibly a firewall problem. Have you tried opening a hole in your firewall for port 1001?
Have you also looked at your java.policy and make sure that it is configured to allow local codebase to open sockets?
as mentioned in comment, you should not use port < 1025 for you applications, since they are always used in deamon processes. However you should test your program like this
1) if you get connection refused then you should check the exception properly, whether client program takes time before generating exception ( that mean request is going to server and then it's giving connection refused), in that case you should try java.policy put following in a file named java.policy
grant {
permission java.net.SocketPermission ":1024-65535",
"connect,accept";
permission java.net.SocketPermission ":80", "connect";
permission java.io.FilePermission "", "read,write,delete";
permission java.security.SecurityPermission "";
};
while compiling use this flag -Djava.security.policy=java.policy
more-over you should also try -Djava.rmi.server.hostname=IP, where IP is clien-ip for client.java and server-ip for server.java
2) if you are immediately getting exception at client side then your request is not going outside your pc, so client has some problem.
check the exception properly and post them over here.
3) though i've not got access denied error, but it seems to have port problem that might be solved using policy or port>1024.
post what are you getting now.