Password authentication socket programming - java

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

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

File transfer Client to Client in JAVA

I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer

multiple messages through the same socket doesn't work

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

Handle java cancel button in two JOptionPane showInputDialog

First, i am sorry maybe the title is wrong. I will explain my problem. I have one joptionpane with showinputdialog component to input server address. I want after click Cancel button, it will return to main window. But in my case, it instead to second joptionpane.
My English is bad :) ...
Anyone can help me ?
This is my code
private static int setPortNumber()
{
String portNumber = JOptionPane.showInputDialog(frame,
"Enter the Port number for server creation","Server Connection\n",
JOptionPane.OK_CANCEL_OPTION);
int PORT = Integer.parseInt(portNumber);
return PORT;
}
private static String setServerName()
{
server_address = JOptionPane.showInputDialog(frame,
"Enter Server Address or PC-Name.", "Server Connection",
JOptionPane.OK_CANCEL_OPTION);
return server_address;
}
private void networking() {
server_address = setServerName();
try {
PORT = setPortNumber();
if (server_address != null) {
sock = new Socket(InetAddress.getByName(server_address) ,
PORT);
}
else {
SocketException sc = new SocketException();
throw sc;
}
// Recieving input and output streams
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
br = new BufferedReader(ir);
pw = new PrintWriter(sock.getOutputStream());
login.setEnabled(true);
incoming.append("Connected to Server.please login.\n");
connect.setEnabled(false);
pw.println("~##~");
pw.flush();
login.requestFocus();
}
private void networking() {
server_address = setServerName();
if(server_address == null || server_address.equals("")){
//Handle what happens when the server name is empty (or the user clicked the cancel button. If you let the execution continue, then the try/catch block below will pop up the second jInputDialog
}
try {
PORT = setPortNumber();
if (server_address != null) {
sock = new Socket(InetAddress.getByName(server_address) ,
PORT);
}
else {
SocketException sc = new SocketException();
throw sc;
}
...
}
Run this example. It works fine
import javax.swing.JOptionPane;
public class NetWorking {
public static String server_address;
public static void main(String[] args) {
networking();
}
private static int setPortNumber()
{
String portNumber = JOptionPane.showInputDialog(null,
"Enter the Port number for server creation","Server Connection\n",
JOptionPane.OK_CANCEL_OPTION);
int PORT = Integer.parseInt(portNumber);
return PORT;
}
private static void setServerName()
{
server_address = JOptionPane.showInputDialog(null,
"Enter Server Address or PC-Name.", "Server Connection",
JOptionPane.OK_CANCEL_OPTION);
}
private static void networking(){
setServerName();
if (server_address == null) {
return;
}
Integer port = setPortNumber();
if (port != null) {
System.out.println(port);
}
}
}

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