multiple messages through the same socket doesn't work - java

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;
}

Related

Having trouble with Java client-server communication, where the out.println seems to be delayed?

I'm confused as to why I cant seem to get the server to output to the client properly. I'm not the most experienced when it comes to java and have exhausted anything I could think of. The other systems in place seem to work fine(The Add/List commands).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoclient;
import java.io.*;
import java.net.*;
/**
*
* #author Leepe
*/
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1248;
public static void main(String[] args) {
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Host ID not found!");
System.exit(1);
}
run();
}
private static void run() {
Socket link = null; //Step 1.
try
{
link = new Socket(host,PORT); //Step 1.
//link = new Socket( "192.168.0.59", PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));//Step 2.
PrintWriter out = new PrintWriter(link.getOutputStream(),true); //Step 2.
//Set up stream for keyboard entry...
BufferedReader userEntry =new BufferedReader(new InputStreamReader(System.in));
String message = "";
String response = "";
while (!message.equals("Stop")) {
System.out.println("Enter message to be sent to server: ");
message = userEntry.readLine();
out.println(message); //Step 3.
// out.flush();
response = in.readLine(); //Step 3.
System.out.println("\nSERVER RESPONSE> " + response);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close(); //Step 4.
}catch(IOException e)
{
System.out.println("Unable to disconnect/close!");
System.exit(1);
}
}
} // finish run method
} //finish the class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoserverthreads;
import java.io.*;
import java.net.*;
/**
*
* #author Leepe
*/
public class TCPEchoServer {
private static ServerSocket servSock;
private static final int PORT = 1248;
private static int clientConnections = 0;
public static void main(String[] args) {
System.out.println("Opening port..."+"\n"+"Listening on port: "+PORT);
try
{
servSock = new ServerSocket(PORT); //Step 1.
}
catch(IOException e)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
synchronized private static void run()
{
Socket link = null; //Step 2.
try
{
link = servSock.accept();
clientConnections++;
String client_ID = clientConnections + "";
Runnable resource = new ClientConnectionRun(link, client_ID);
Thread t = new Thread (resource);
t.start();
}
catch(IOException e1)
{
e1.printStackTrace();
try {
System.out.println("\n* Closing connection... *");
link.close(); //Step 5.
}
catch(IOException e2)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
} // finish run method
} // finish the class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoserverthreads;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
/**
*
* #author Leepe
*/
public class ClientConnectionRun implements Runnable {
Socket client_link = null;
String clientID;
public static List<String> currentList = new ArrayList<String>();
String[] parts;
String part1;
String part2;
String part3;
String message = "";
public ClientConnectionRun(Socket connection, String cID) {
this.client_link = connection;
clientID = cID;
}
#Override
synchronized public void run() {
try{
BufferedReader in = new BufferedReader( new InputStreamReader(client_link.getInputStream())); //Step 3.
PrintWriter out = new PrintWriter(client_link.getOutputStream(),true); //Step 3.
System.out.println("\n* started connection with the client " + clientID + " ... *");
while (!message.equals("Stop")){//Step 4.
message = in.readLine();
// out.flush();
System.out.println("\n Message received from client: " + clientID + " - "+ message);
out.println("\n Echo Message: " + message);
//out.flush();
if(message.contains(";")){
// String userinput = message;
// String item = message;
// System.out.println("Contains ;");
String[] parts = message.split(";");
String part1 = parts[0];
String part2 = parts[1];
System.out.println(part1);
System.out.println(part2);
if(parts.length >= 3 && part1.equals("add")){
String part3 = parts[2];
System.out.println(part1);
System.out.println(part2);
System.out.println(part3);
currentList.add(part2+" - "+part3);
//AddItem();
}
else if(parts.length <= 2 && part1.equals("list") ){
System.out.println("list command working");
//ListItem();
System.out.println();
System.out.println("----------------------");
System.out.println("To-Do List");
System.out.println("----------------------");
int number = 0;
for (Iterator<String> it = currentList.iterator(); it.hasNext();) {
message = it.next();
if(message.contains(part2)){
System.out.println(++number + " " + message);
}
}
System.out.println("----------------------");
}
else {
System.out.println("\n Don't add a description if you are searching for a date");
}
}
else if(!message.contains(";")){
System.out.println("\n Unknown command, Try using 'add' or 'list' followed by a ' ; ' as listed above ");
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try {
System.out.println("\n* Closing connection with the client " + clientID + " ... *");
client_link.close(); //Step 5.
}
catch(IOException e)
{
System.out.println("Unable to disconnect!");
}
}
}
}
I want the server to be able to output info to the client that's connected. What's happening is that the server will output the info eventually but requires me to enter several more inputs, i'm not sure how its delayed and any help would be appreciated.
Leaving everything else untouched, simply changing your line out.println("\nEcho Message: " + message); in your Class ClientConnectionRun to out.println("Echo Message: " + message); will fix this.
Essentially, what goes wrong is that your line response = in.readLine(); in the client terminates when it encounters a line-feed. So, if you begin your response with a line-feed, it will terminate instantly and is thus always trailing by one line, which is why you will only see the actual response the next time you enter some input.
From the doc of java.io.BufferedReader.readLine():
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), a carriage return
followed immediately by a line feed, or by reaching the end-of-file
(EOF).
Also, some general input:
You can drastically improve your code by using try-with-resources statements (since Java 8). This way you can avoid the "nasty" nested try-catch-finally constructs to handle your streams. For your Client for example you could simplify do:
try (Socket link = new Socket(host, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(), true);
BufferedReader userEntry = new BufferedReader(new InputStreamReader(System.in))) {
And all you need at the end is this:
} catch (IOException e) {
e.printStackTrace();
}

json file not arriving complete when using sockets

I have a stream of video. And every frame I need to send a small json file with data from that frame, speed it´s crucial. Whats the best way to do this?
My Server is something like this. Waits for a json file and then has to send that json file to a python application.
public class ServerClass {
public static void main(String[] args) {
Marcoserver mimarco=new Marcoserver();
}
}
class Marcoserver implements Runnable {
public Marcoserver(){
Thread miHilo = new Thread(this);
miHilo.start();
}
public void run() {
try {
ServerSocket server = new ServerSocket(7777);
while (true) {
Socket miSocket = server.accept();
BufferedReader entrada = new BufferedReader(new InputStreamReader(miSocket.getInputStream(), "UTF8"));
String mensaje = entrada.readLine();
JSONObject obj;
obj = new JSONObject(mensaje);
System.out.println(obj);
ConectorSocket cntor = new ConectorSocket("localhost", 6363);
cntor.Conectar();
cntor.Send(mensaje);
cntor.Close();
miSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ConectorSocket{
private String host;
private int port;
Socket sockSend;
public ConnectClass(String hst, int prt ) {
this.host = hst;
this.port = prt;
}
public void Conectar() {
this.sockSend = new Socket(this.host, this.port);
}
public void Send(String mensaje) {
DataOutputStream flujo_salida = new DataOutputStream(sockSend.getOutputStream());
flujo_salida.writeBytes(mensaje);
flujo_salida.close();
}
public boolean Close() {
this.sockSend.close();
}
}
This is the python app simplified:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 6666))
serversocket.listen()
while True:
connection, address = serversocket.accept()
buf = connection.recv(2048)
if len(buf) > 0:
print(buf.decode())
My problem is that the python app prints incomplete information such as:
{"keyword"
{"keyword": [[14, 1, -1]]}
{"keyword": [[14,
instead of:
{"keyword":[]}
{"keyword":[[14,1,-1]]}
{"keyword":[[14,2,-1]]}
There's nothing wrong with your Java code, but your Python code is not good:
while True:
connection, address = serversocket.accept()
buf = connection.recv(2048)
if len(buf) > 0:
print(buf.decode())
That will print just the first received TCP packet for each connection.
You need to continue calling recv until it returns 0:
while True:
connection, address = serversocket.accept()
msg = []
while True:
buf = connection.recv(65536)
if (len(buf) == 0):
break
msg.append(buf)
print(''.join(msg))
connection.close()
You also need to close each connection.

Password authentication socket programming

I have 3 classes (Client, Server, and Protocol) that allow a user to login and send a message to another user. I'm trying to add a password feature to the program but nothing I've tried has worked so far. I've added my code below, I want to prompt the user to put the password in after the error checking on the username has been done. The password should be compared and checked that it is a match, and only then should the user be able to view their messages and send messages.
Any tips would really be appreciated, thanks!
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String messages = "";
// Makes sure there are only two arguments entered
if(args.length != 2) {
System.err.println("Usage: java Client <host name> <port number>");
System.exit(1);
}
// Stores the command line arguments for readability further in the program
String host = args[0];
int port = Integer.parseInt(args[1]);
try (
// Creates the socket to be used
Socket s = new Socket(host, port);
// Reader and Writer to talk with Server
PrintWriter pw =
new PrintWriter(s.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(s.getInputStream()));
) {
// Reader to read from standard input (keyboard)
BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
// User interface
while (true) {
System.out.println("Please enter your username: ");
String username = keyboard.readLine();
// Check that the login is valid
if (username == null) {
System.out.println("No username entered");
}
else if (username.contains(" ")) {
System.out.println("Username cannot contain spaces");
}
// Send username to server and return number of messages
else {
pw.println(username);
messages = bf.readLine();
System.out.println("You have " + Integer.parseInt(messages) + " messages");
break;
}
}
// Enable the user to continue reading and composing messages until
// they choose to exit
while (true) {
System.out.println("Would you like to READ, COMPOSE or EXIT?");
String choice = keyboard.readLine();
// Shows the messages left for the user
if (choice.equals("READ")) {
pw.println("READ");
messages = bf.readLine();
if (messages == "0") {
System.out.println("NO MESSAGES");
}
else {
String incoming = bf.readLine();
System.out.println(incoming);
incoming = bf.readLine();
System.out.println(incoming);
}
}
// Allows user to write a message to another user
else if (choice.equals("COMPOSE")) {
pw.println("COMPOSE");
System.out.println("Enter message recipient");
String recipient = keyboard.readLine();
if (recipient == null) {
System.out.println("No recipient username entered");
}
else if (recipient.contains(" ")) {
System.out.println("Recipient username cannot contain spaces");
}
else {
pw.println(recipient);
System.out.println("Enter message to be sent");
String im = keyboard.readLine();
pw.println(im);
System.out.println(bf.readLine());
}
}
else if (choice.equals("EXIT")) {
pw.println("EXIT");
System.exit(1);
}
else {
System.out.println("Error: you must either READ, COMPOSE or EXIT");
}
}
}
// Catches the exception in which the server cannot be found
catch(IOException e) {
System.out.println("Error, could not connect to Server");
System.exit(1);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
String request;
// Makes sure that the user has specified the correct number of command line arguments
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
try (
// Creates a server socket and waits for a connection
ServerSocket ss = new ServerSocket(port);
// A socket to communicate with the client
Socket cs = ss.accept();
// Reader and Writer to talk with Client
PrintWriter pw =
new PrintWriter(cs.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(cs.getInputStream()));
)
// Links the server to the protocol
{
Protocol protocol = new Protocol();
protocol.storeUsername(bf.readLine());
pw.println(protocol.messagesNumber());
// Loop through user input until EXIT is entered
while (true) {
request = bf.readLine();
// Controls output if user inputs READ
if (request.equals("READ")) {
pw.println(protocol.messagesNumber());
pw.println(protocol.readSender());
pw.println(protocol.readMessage());
}
// Controls input if user inputs COMPOSE
else if (request.equals("COMPOSE")) {
String sender = bf.readLine();
String message = bf.readLine();
if (protocol.append(sender, message)) {
pw.println("MESSAGE SENT");
}
else {
pw.println("MESSAGE FAILED");
}
}
// Exits the server
else {
System.exit(1);
}
}
}
// Catches the exception in which the server cannot find a client
catch(IOException e) {
System.out.println("Failed to find a client");
System.exit(1);
}
}
}
Protocol.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Protocol {
private String username;
private String recipient;
private String sender;
private HashMap<String, ArrayList<String>> senderMap = new HashMap<String, ArrayList<String>>();
private HashMap<String, ArrayList<String>> messageMap = new HashMap<String, ArrayList<String>>();
// Stores the username for the logged in user
public void storeUsername(String user) {
username = user;
}
// Stores the recipient name
public void storeRecipient(String name) {
recipient = name;
}
// Returns how many messages the logged in user has
public int messagesNumber() {
if(messageMap.containsKey(username))
return messageMap.get(username).size();
else
return 0;
}
public boolean append(String recipient, String message) {
boolean success = false;
// If there is an entry for that name, just add the message to the end
if(messageMap.containsKey(recipient)) {
senderMap.get(recipient).add(username);
messageMap.get(recipient).add(message);
success = true;
}
// If there is no entry for that name, create a new entry with a list of messages and add the first message
else {
senderMap.put(recipient, new ArrayList<String>());
senderMap.get(recipient).add(username);
messageMap.put(recipient, new ArrayList<String>());
messageMap.get(recipient).add(message);
success = true;
}
return success;
}
public String readSender() {
// If the user has an entry and has at least 1 sender, return the least recent sender and then remove it (the sender first in the list)
if(senderMap.containsKey(username)) {
if(senderMap.get(username).size() > 0) {
String temp = senderMap.get(username).get(0);
senderMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
public String readMessage() {
// If the user has an entry and has at least 1 unread message, return the least recent unread message and then remove it (the first message in the list)
if(messageMap.containsKey(username)) {
if(messageMap.get(username).size() > 0) {
String temp = messageMap.get(username).get(0);
messageMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
}

Java Client-Server and Observer

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.

Running a Client-Server Chat program

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.

Categories

Resources