FileZilla won't react on commands from my java FTP server - java

I write my own Java FTP server. Until recently I used PUttY to debug my control telnet connection and everything seemed fine - I had successful two-way communication. Now I try to debug my server with FileZilla, but it does not seem to read my text, nor to send some to server, so it just hangs and wait for something.
Control connection class
public class ControlConnection extends Thread {
private enum OperationMode {
ACTIVE, PASSIVE
}
private final Map<String, Supplier<String>> COMMANDS;
private String[] userTokens;
private User user;
private String userLogin;
private boolean authenticated;
private boolean dataConnected;
private boolean userExists;
private final Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private DataConnection ftpSession;
private OperationMode operationMode;
private String errorMessage;
public ControlConnection(Socket socket) {
super(ControlConnection.class.toString());
this.socket = socket;
// constants initialization
authenticated = false;
dataConnected = false;
// commands initialization
COMMANDS = new HashMap<>();
// commands init
}
#Override
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
sendGreetings();
IOProcessing.writeBytes(outputStream, pasvCommand());;
boolean running = true;
while (running) {
sendGreetings();
String input = IOProcessing.readBytes(inputStream);
if (!(input.equals("")))
System.out.println(input);
if (!checkInput(input))
continue;
userTokens = input.split(" ");
String command = userTokens[0].toUpperCase();
String answer = COMMANDS.get(command).get();
outputStream.writeBytes(answer);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
private boolean commonCheck() {
// some checks
return true;
}
private String getErrorMessage() {
return errorMessage;
}
public void sendGreetings() {
String greetings = String.format("220 Control connection established: %s", getConnectionInfo());
IOProcessing.writeBytes(outputStream, greetings);
}
public String getConnectionInfo() {
String info = String.format("%s: %d %s",
socket.getInetAddress().toString(), socket.getPort(), user != null ? user.getUsername(): "");
return info;
}
// input/output proccessing functions
public boolean checkInput(String input) {
// checks
return true;
}
// commands functions
private String pasvCommand() {
if (operationMode == OperationMode.PASSIVE) {
errorMessage = "Already in passive mode.%n";
return errorMessage;
}
String answer;
new ListenToSocket().start();
answer = String.format("227 Entering Passive Mode (%s, %d)",
"127.0.0.1", DataConnection.PORT);
operationMode = OperationMode.PASSIVE;
return answer;
}
private class ListenToSocket extends Thread {
public ListenToSocket() {
}
#Override
public void run() {
try {
ServerSocket ftpSocket =
new ServerSocket(DataConnection.PORT);
ftpSession =
DataConnection.getDataConnection(ftpSocket.accept());
if (ftpSession != null) {
ftpSession.start();
dataConnected = true;
String greetings = "Data connection established: " + ftpSession.getConnectionInfo();
IOProcessing.writeBytes(outputStream, greetings);
} else {
dataConnected = false;
}
} catch (IOException e) {
System.out.print(e);
}
}
}
also, server does not get user credentials, entered in FileZilla - input from server is always empty
IOProcessing class
public class IOProcessing {
private static final Charset UTF8_CHARSET;
static {
UTF8_CHARSET = Charset.forName("UTF-8");
}
public static String readBytes(DataInputStream inputStream) {
String result = "";
try {
int len = inputStream.available();
if (len == 0) {
return result;
}
byte[] byteInput = new byte[len];
inputStream.readFully(byteInput, 0, len);
result = new String(byteInput, "UTF-8").trim();
} catch (IOException e) {
System.err.println(e);
}
return result;
}
output FileZlla log
Status: Resolving address of localhost
Status: Connecting to [::1]:21...
Status: Connection established, waiting for welcome message.

You didn't show us the writeBytes. So I can only guess that you are not sending \r\n after the messages sent to the client. Particularly after the welcome message. So FileZilla keeps waiting forever for it, as any FTP client would do.

Related

Socket Server via Singleton with parameters from properties file

I am going to run Socket Server via Singleton Pattern because I have multiple threads, and every time I call it, I want to use the same socket server. This is SocketSingleton.java class :
public class SocketSingleton {
private static ServerSocket serverSocket = null;
private SocketSingleton() {}
public static synchronized ServerSocket getServerSocket() throws IOException {
PropertiesKey prop = new PropertiesKey();
if (serverSocket == null) {
serverSocket = new ServerSocket(prop.getSocketPort());
}
return serverSocket;
}
}
But I've noticed that I should get my few values from configuration.properties like SOCKET_PORT=2203
I can get the values from configuration with the code bellow
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static Properties defaultProps = new Properties();
static {
try {
String propertiesDirectory = "src/main/resources/configuration.properties";
FileInputStream in = new FileInputStream(propertiesDirectory);
if (in == null) {
System.out.println("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
return "Sorry, unable to find " + key ;
}
}
This is an enum of Socket Port.
public enum CONFIG { SOCKET_PORT}
public class PropertiesKey {
private PropertiesAlgorithm propertiesAlgorithm;
public int getSocketPort(){
propertiesAlgorithm = new PropertiesAlgorithmImpl();
return Integer.parseInt(propertiesAlgorithm.getValuesFromProperties(CONFIG.SOCKET_PORT.name()));
}
In the SocketSingleton class, I am calling socket port like this:
serverSocket = new ServerSocket(prop.getSocketPort());
What is the possible reason that I can't get the socket port parameters from configuration.properties?
I fixed the class bellow with input stream and it worked:
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static final Logger logger = LoggerFactory.getLogger(PropertiesAlgorithmImpl.class);
private static Properties defaultProps = new Properties();
static {
String propertiesDirectory = "config.properties";
try (InputStream input = PropertiesAlgorithmImpl.class.getClassLoader().getResourceAsStream(propertiesDirectory)) {
if (input == null) {
logger.info("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(input);
input.close();
} catch (Exception e) { logger.info(String.valueOf(e.getStackTrace())); }
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
logger.info("Sorry, unable to find " + key);
return "Sorry, unable to find " + key ;
}

JAVA Send an object to all clients

I try to make a chat. When a client send a message to the server, it is working, the server receives the message. So I would like to send this message all the clients. I tried many things but they are not working... Just the client which sends the message, it receives this message
Can You help me please ?
Thanks in advance
PS : Sorry for my bad English
This is the result in the console :
http://i.stack.imgur.com/VS2wf.png
MainClient
public class MainClient {
/**
* #param args the command line arguments
* #throws java.io.IOException
* #throws java.lang.ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean stop = false;
Socket socket;
Scanner nickScan;
String nick;
socket = new Socket(InetAddress.getLocalHost(), 2009);
System.out.println("Hi, what is your name ?");
nickScan = new Scanner(System.in);
nick = nickScan.nextLine();
User u = new User(nick, false, false, true);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
EmissionThread e = new EmissionThread(u, socket);
e.start();
while(!stop){
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
}
//socket.close();//On ferme les connexions
}
}
MainServer
public class MainServer extends Thread {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO code application logic here
ConnectionThread c = new ConnectionThread();
c.start();
}
}
ConnectionThread
public class ConnectionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
Session s = new Session("#upec");
public ConnectionThread() throws IOException {
this.socketserver = new ServerSocket(2009);
}
public ServerSocket getSocketserver() {
return socketserver;
}
#Override
public void run() {
while (!stop) {
try {
socketduserveur = socketserver.accept(); //On accepte les connexions
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
User u = (User)ois.readObject();
System.out.println(u.getNick() + " c'est connecté");
s.addUserList(u);
if (s.listAlone()) {
System.out.println("Vous etes admin");
u.setAdmin(true);
}
ReceptionThread r = new ReceptionThread(socketduserveur);
r.start();
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ReceptionThread
public class ReceptionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
public ReceptionThread(Socket socketduserveur) {
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(ReceptionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
EmissionThread
public class EmissionThread extends Thread {
private User u;
private Socket socketduserveur;
private static final boolean stop = false;
public EmissionThread(User u, Socket socketduserveur) {
this.u = u;
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
Scanner msgScan;
String msg;
msgScan = new Scanner(System.in);
msg = msgScan.nextLine();
Message m = new Message(u.getNick(), msg);
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException ex) {
Logger.getLogger(EmissionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Message
public class Message implements Serializable {
private String nick;
private String msg;
public Message(String nick, String msg) {
this.nick = nick;
this.msg = msg;
}
}
Session
public class Session implements Serializable {
private String name;
private ArrayList<String> listSession = new ArrayList();
private ArrayList<User> listUser = new ArrayList();
public Session(String name) {
this.name = name;
}
public void addSession(String name){
listSession.add(name);
}
public void deleteSession(String name){
for(String s : listSession){
if(name.equals(s)){
listSession.remove(s);
}
}
}
public boolean existSession(String name){
for(String s : listSession){
if(name.equals(s)){
return true;
}
}
return false;
}
public void addUserList(User u){
listUser.add(u);
}
public boolean listAlone(){
int compteur = 0;
for(User u : listUser){
compteur++;
}
return compteur == 1;
}
}
User
public class User implements Serializable {
private String nick;
private final Session session;
private boolean admin, moderator, voice;
public User(String nick, boolean admin, boolean moderator, boolean voice) {
this.nick = nick;
this.admin = admin;
this.moderator = moderator;
this.voice = voice;
this.session = new Session("#upec");
}
}
You can use websockets on tomcat for this. If you download tomcat there is a chat app already built as an example

ReadObject returns OptionalDataException

We are trying to send an object from an android Bluetooth client to a desktop Bluetooth server. We are trying to do this through the ObjectInputStream and ObjectOutput Stream. We are also very new to Bluetooth development, and have tried looking online for different examples and solutions.
Here is our code,
Android Code:
private static 1.5.0/docs/api/java/util/UUID.html">UUID generalUuid = 1.5.0/docs/api/java/util/UUID.html">UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static BluetoothSocket socket;
private static BluetoothSocket getBluetoothSocket(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.cancelDiscovery();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
if(device.getName().equalsIgnoreCase(("mint-0"))){
try {
return device.createRfcommSocketToServiceRecord(generalUuid);
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
return null;
}
}
}
}
return null;
}
public static boolean sendData(1.5.0/docs/api/java/lang/String.html">String first, 1.5.0/docs/api/java/lang/String.html">String last, int age){
socket = getBluetoothSocket();
try {
socket.connect();
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
// TODO Auto-generated catch block
socket = null;
}
if(socket != null){
try {
1.5.0/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream oos = new 1.5.0/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream(socket.getOutputStream());
oos.writeChars("X");
//send serializable object
personTest person = new personTest(first, last, age);
oos.writeObject(person);
oos.flush();
oos.close();
socket.close();
return true;
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
socket = null;
return false;
}
}else{
return false;
}
}
PC Code:
public class DataServer {
static final String serverUUID = "11111111111111111111111111111123";
public static void main(String[] args) throws IOException {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service
System.out.println("Setting Discoverable");
String url = "btspp://localhost:" + serverUUID + ";name=BlueToothServer";
StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url);
System.out.println("Server: " + url);
StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
System.out.println("Client Connected");
//=== At this point, two devices should be connected ===//
ObjectInputStream ois = new ObjectInputStream(connection.openInputStream());
personTest obj = null;
System.out.println("Waiting for Object");
//while(true){
try{
obj = (personTest) ois.readObject();
if(obj.getName() != "Gregg Miller"){
System.err.println("Name " + obj.getName() + " incorrect");
}
} catch(ClassNotFoundException cnfe){
System.err.println("cnfe "+cnfe.getMessage());
}
catch(InvalidClassException ice){
System.err.println("ice "+ice.getMessage());
}
catch(StreamCorruptedException sce){
System.err.println("sce "+sce.getMessage());
}
catch(IOException ioe){
System.err.println("ioe "+ioe.getMessage());
System.err.println(ioe.toString());
System.err.println("ODE Length: " +((OptionalDataException)ioe).length);
System.err.println("ODE EOF: " +((OptionalDataException)ioe).eof);
}
//}
System.out.println("Recieved, closing connection");
connection.close();
}
}
The output of the program after running both the android app and the desktop program are as followed:
ioe null
java.io.OptionalDataException
ODE Length: 2
ODE EOF: false
As requested, here is the PersonTest code:
package edit.rit.ce.whud;
import java.io.Serializable;
public class personTest extends Object implements Serializable {
private String firstName;
private String lastName;
private int age;
public personTest(String first, String last, int age){
this.firstName = first;
this.lastName = last;
this.age = age;
}
public String getName(){
return firstName +" "+ lastName;
}
public int getAge(){
return age;
}
}
Remove this:
oos.writeChars("X");
You're confusing the readObject() method at the other end. Or else read those chars at the other end.

ClassNotFoundException on the server when reading from ObjectInputStream

Based on this tutorial and another tutorial that unfortunately I can't get my hands on right now, I've created my Client-Server application but instead of sending string messages, the client asks for data(using Object Input/Output Streams) from the server using a custom class "Message".
First I created, the basic concept of it, using simple Java and tested both the server and the client on my computer, and displayed the data my client received in the console output. Everything worked out great, so I started to make the transition to Android(for the client). Trying to use the AsycTask, as show in the linked tutorial, I've managed so far to establish the connection between the client and the server. But I'm having a problem getting my server to read my "Message" object. Here are my classes:
Server:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class T_Server extends Thread {
private static int port = 4444;
private ServerSocket srvSock = null;
private Socket clntSock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
private Message msgIn;
private Object objSend;
public static void main(String[] args) {
OnMessageReceived _msgListener=new OnMessageReceived();
T_Server server=new T_Server(_msgListener);
server.start();
}
public T_Server(OnMessageReceived _msgListener) {
this.msgListener = _msgListener;
}
public void send(Object _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
} catch (IOException ex) {
Logger.getLogger(T_Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void run() {
running = true;
try {
srvSock = new ServerSocket(port);
System.out.println("Server startet. IP : " + InetAddress.getLocalHost() + ", Port : " + srvSock.getLocalPort());
System.out.println("\nWaiting for a client ...");
clntSock = srvSock.accept();
System.out.println("\nClient accepted: " + clntSock);
try {
out = new ObjectOutputStream(clntSock.getOutputStream());
in = new ObjectInputStream(clntSock.getInputStream());
while (running) {
msgIn = (Message) in.readObject();
System.out.println(msgIn.toString());
objSend = msgListener.messageReceived(msgIn);
send(objSend);
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
clntSock.close();
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
}
I use the same Message class both on the Server and on the Client
Message Class:
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String sender, content, type;
public Message(String sender, String type, String content){
this.sender = sender; this.type=type; this.content = content;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"'}";
}
}
I have also created a class to handle the Messages, on the server side, called OnMessageReceived.
P.S. In this class there are fields and some options that have to do with my backend database.
OnMessageReceived:
import java.sql.SQLException;
import java.util.regex.Pattern;
public class OnMessageReceived {
public Object messageReceived(Message message) throws SQLException {
Message _msg = message;
Database db = new Database();
Object objReturn;
String strResult;
boolean addResult;
final Pattern pattern = Pattern.compile("\\[.*?&");
final String[] result;
if (_msg.type.equals("getUsers")) {
objReturn = db.getUsers();
return objReturn;
} else if (_msg.type.equals("getFriends")) {
objReturn = db.getFriends(_msg.sender);
return objReturn;
} else if (_msg.type.equals("addFriend")) {
String _UserName, _UserNameFriend;
_UserName = _msg.sender;
_UserNameFriend = _msg.content;
addResult = db.addFriend(_UserName, _UserNameFriend);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("addUser")) {
String _UserName, _Password, _Phone;
result = pattern.split(_msg.content);
_UserName = _msg.sender;
_Password = result[0];
_Phone = result[1];
addResult = db.addUser(_UserName, _Password, _Phone);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("Login")) {
boolean isUser;
String _UserName;
_UserName = _msg.sender;
isUser = db.isUser(_UserName);
if (isUser) {
strResult = "Login Successfull";
return strResult;
} else if (!isUser) {
strResult = "Login failed";
return strResult;
}
}
return null;
}
}
For the client side(on the Android) it's very simillar to the one in the linked tutorial.
The difference is that I only have 2 buttons, one to connect to the server and one to send my message, which is an instance of my Message class.
Client:
import java.io.*;
import java.net.*;
import android.util.Log;
public class T_Client {
private static final String TAG = "MyActivity";
private static String serverIP = "192.168.1.11";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
Object objIn, objReceived;
public T_Client(OnMessageReceived _msgListener){
this.msgListener=_msgListener;
}
public void send(Message _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i(TAG,"Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e(TAG,ex.toString());
}
}
}
public void stopClient(){
running = false;
}
public void run(){
running = true;
try {
//here you must put your computer's IP address.
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
sock = new Socket(serverAddr, port);
try {
//send the message to the server
out =new ObjectOutputStream(sock.getOutputStream());
//receive the message which the server sends back
in =new ObjectInputStream(sock.getInputStream());
Log.i("TCP Client", "C: Connected.");
//in this while the client listens for the messages sent by the server
while (running) {
objIn = in.readObject();
if (objIn != null && msgListener != null) {
//call the method messageReceived from MyActivity class
msgListener.messageReceived(objIn);
}
objIn = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
sock.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
public void messageReceived(Object objReceived);
}
}
Main Activity:
import java.io.IOException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private static final String TAG = "MyActivity";
private T_Client client;
private Message msgSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View v) throws IOException {
new connectTask().execute("");
}
public void btnSend(View v) throws IOException {
msgSend=new Message("Setlios", "getUsers", "");
if(client!=null){
client.send(msgSend);
}
}
public class connectTask extends AsyncTask<Object,Object,T_Client> {
#Override
protected T_Client doInBackground(Object... objIn) {
//we create a TCPClient object and
client = new T_Client(new T_Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(Object objIn) {
//this method calls the onProgressUpdate
publishProgress(objIn);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
Log.i(TAG,values.getClass().getName().toString());
}
}
}
When I hit the "Send" button I get this error on the server console which points me to the point where I read the object read from the ObjectInputStream and pass it an instance of the Message class but I can't understand what the problem is. I also noticed that it shows this "in.neverhide.connect" which is the package name of the project for my android client
java.lang.ClassNotFoundException: in.neverhide.connect.Message
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:622)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1593)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Objects_WORKING.T_Server.run(T_Server.java:61)
Ok after searching around I found this post and the answer from Akinsola 'mys Tunmise. I've made the Message class into a jar and used it as an external reference in both the client and the server.

Java Telnet Library

I am really not clear on explaining this requirement but what I need basically is a JSP page that connects to a Unix server and gets the word count of a file and displays on the JSP page. I have looked on various questions here but nothing helped. A sample code would be of much help. Thanks
Kavin, I guess you must have found some other solution or moved on by now. However, I just came across a requirement that led me to this page.
I looked through the somewhat smuckish responses on this page and many others but could not find a simple to use Telnet client at all.
I spent a little bit of time and wrote a simple client on top of Commons Net's solution. Please forgive the System.out and System.err in the code, I got it to barely work.
public static void main(String[] args) throws Exception {
SimpleTelnetClient client = new SimpleTelnetClient("localhost", 2323);
client.connect();
String result = client.waitFor("login:");
System.out.println("Got " + result);
client.send("username");
result = client.waitFor("Password:");
System.out.println("Got " + result);
client.send("password");
client.waitFor("#");
client.send("ls -al");
result = client.waitFor("#");
System.out.println("Got " + result);
client.send("exit");
}
Not sure if it will help you anymore, but perhaps it could be a starting point for others.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
public class SimpleTelnetClient {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final SimpleTelnetClient checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(SimpleTelnetClient checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private final SimpleTelnetClient checker;
private final TelnetClient tc;
TelnetReader(SimpleTelnetClient checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
ret_read = instr.read(buff);
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
}
} while (ret_read >= 0);
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public SimpleTelnetClient(String host, int port) {
this.host = host;
this.port = port;
}
protected void stop() {
responder.isKeepRunning = false;
responder.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws Exception {
tc = new TelnetClient();
TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
try {
tc.addOptionHandler(ttopt);
tc.addOptionHandler(echoopt);
tc.addOptionHandler(gaopt);
} catch (InvalidTelnetOptionException e) {
System.err.println("Error registering option handlers: " + e.getMessage());
}
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
}
Why wouldn't you just use an open source telnet client. There is bound to be several to choose from. Google lists many.

Categories

Resources