at the moment I am creating a simple chat program that will allow you to communicate between a server. I am having an issue accessing the username variable when it is used in one file in another file. The user will enter his name, this is done in the ChatGUI file, then when he enters the chat room a EchoFrame is created, which is in the EchoFrame file. Also in the EchoFrame file, I want to append the username to the users message, and also announce when they connect to the chatroom and when they leave the chat room. I hope I was clear on explaining my issue, any other information needed please let me know!
EchoFrame
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class EchoFrame extends Frame{
EchoPanel ep;
Button sendMessage;
public EchoFrame(){
setSize(500,500);
setTitle("Echo Client");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
ep = new EchoPanel();
add(ep, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args){
EchoFrame ef = new EchoFrame();
}
}
class EchoPanel extends Panel implements ActionListener, Runnable{
TextField tf;
TextArea ta;
Button connect, disconnect;
Socket s;
BufferedReader br;
PrintWriter pw;
Thread t;
String fromServer;
String username;
public EchoPanel(){
setLayout(new BorderLayout());
tf = new TextField();
tf.setEditable(false);
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
ta = new TextArea();
ta.setEditable(false);
add(ta, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
connect = new Button("Connect");
connect.addActionListener(this);
buttonPanel.add(connect);
disconnect = new Button("Disconnect");
disconnect.setEnabled(false);
disconnect.addActionListener(this);
buttonPanel.add(disconnect);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == connect){
try{
s = new Socket("127.0.0.1", 8189);
ta.append(username + " has entered the chat room. \n");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
t = new Thread(this);
t.start();
tf.setEditable(true);
connect.setEnabled(false);
disconnect.setEnabled(true);
}else if(ae.getSource() == disconnect){
try{
pw.close();
br.close();
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
t = null;
ta.append(username + " has disconnected from chat room. \n");
tf.setEditable(false);
connect.setEnabled(true);
disconnect.setEnabled(false);
}else if(ae.getSource() == tf){
String fromTf = tf.getText();
pw.println(fromTf);
tf.setText("");
}else{
//additional events
}
}
public void run (){
fromServer = "";
try{
while((fromServer = br.readLine()) != null){
ta.append(username + ":" + fromServer + "\n");
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
ChatGUI
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ChatGUI extends JFrame {
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
JTextField usernameField;
String username;
public ChatGUI() {
setTitle("Chat Program");
setSize(500, 120);
cardPanel = new JPanel();
cl = new CardLayout();
cardPanel.setLayout(cl);
JPanel chooseUsername = new JPanel();
JLabel usernameLabel = new JLabel("Please enter your username:");
chooseUsername.add(usernameLabel);
cardPanel.add(chooseUsername, "Log in");
usernameField = new JTextField(15);
usernameField.setEditable(true);
add(usernameField, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton logInBtn = new JButton("Enter Chat Room");
buttonPanel.add(logInBtn);
logInBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));
username = usernameField.getText(); //gets username
EchoFrame ef = new EchoFrame(); //creates message room
}
});
getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
ChatGUI cl = new ChatGUI();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
Chat Server
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer{
Socket s;
ArrayList <ChatHandler>handlers;
public ChatServer(){
try{
ServerSocket ss = new ServerSocket(8189);
handlers = new ArrayList<ChatHandler>();
for(;;){
s = ss.accept();
new ChatHandler(s, handlers).start();
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args){
ChatServer tes = new ChatServer();
}
}
Chat Handler
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatHandler extends Thread{
Socket s;
BufferedReader br;
PrintWriter pw;
String temp;
ArrayList <ChatHandler>handlers;
public ChatHandler(Socket s, ArrayList <ChatHandler>handlers){
this.s = s;
this.handlers = handlers;
}
public void run(){
try{
handlers.add(this);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
temp = "";
while((temp = br.readLine()) != null){
for (ChatHandler ch : handlers){
ch.pw.println(temp);
}
System.out.println(temp);
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}finally{
handlers.remove(this);
}
}
}
Make userName static and access it via ChatUI.userName. In actuality, userName shouldn't be in ChatUI. Alternatively, a more heavyweight option would be to get MySQL, set up a database, and connect to it via JDBC, if you're going to have more than one user.
You can also try and follow from these examples: Simple Client And Server Chat Program and Creating a simple Chat Client/Server Solution. They cover key topics, such as multithreading.
I think you should have a server program and a client program, so all variables you need to send to each client can be into the server.
When a client conect to the server a you add that client(username,ipadress,whatever) to a list of connected clients and create a new thread to listen/send to that client. then from the server you can send to all users(threads) the Username and what he wrote if u have a function sendToAll(idThreadSender, threadX.text) or you can sendtothread(threadX,threadY.text) well i think you have a bad structure, thats all.
hope i helped.
Related
I am creating a web browser in java and am receiving the following error when I attempt to run it:
Exception in thread "main" java.net.MalformedURLException: no protocol:
I have not been able to find an answer to my particular problem but I believe it has something to do with my socket. Do I simply need to add a MalformedURLException? Any help is appreciated.
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Browser extends JFrame {
public JPanel addressPanel, windowPanel;
public JLabel addressLabel;
public JTextField textField;
public JEditorPane windowPane;
public JScrollPane windowScroll;
public JButton addressButton;
private Search search = new Search();
public Browser() throws IOException {
addressLabel = new JLabel(" address: ", SwingConstants.CENTER);
textField = new JTextField("Enter a web address..");
textField.addActionListener(search);
addressButton = new JButton("Go");
addressButton.addActionListener(search);
windowPane = new JEditorPane("");
windowPane.setContentType("text/html");
windowPane.setEditable(false);
addressPanel = new JPanel(new BorderLayout());
windowPanel = new JPanel(new BorderLayout());
addressPanel.add(addressLabel, BorderLayout.WEST);
addressPanel.add(textField, BorderLayout.CENTER);
addressPanel.add(addressButton, BorderLayout.EAST);
windowScroll = new JScrollPane(windowPane);
windowPanel.add(windowScroll);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(addressPanel, BorderLayout.NORTH);
pane.add(windowPanel, BorderLayout.CENTER);
setTitle("Web Browser");
setSize(1000, 1000);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Search implements ActionListener {
public void actionPerformed(ActionEvent ea) {
String line;
try {
Socket socket = new Socket(textField.getText(), 80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.print("GET / HTTP/1.1\r\n");
out.print(textField.getText() + "\r\n\r\n");
out.flush();
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
Browser browser = new Browser();
}
}
The problem was because the line bellow:
windowPane = new JEditorPane("");
Just change to
windowPane = new JEditorPane();
According to JEditorPane constructor javadoc:
Creates a JEditorPane based on a string containing a URL specification.
#param url the URL
#exception IOException if the URL is null or cannot be accessed
I have a chat client program I am working on and currently I can get the text pane, text input on the left. I can add buttons and change the background color to the right but I can not get an image to display on the right. There is more than one way to skin a cat on this from what I've read but I'm trying to stick with the setup I currently have so I don't have to rewrite everything. I understand the basics of Java (OOP) and how it works. I'm just lost as to how to format image icon and get this image to display. Here is the code: I am compiling with IntelliJ.
package edu.lmu.cs.networking;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ChatClient {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("Chatter");
private JTextField textField = new JTextField(20);
private JTextArea messageArea = new JTextArea(8, 40);
private JPanel panel;
private JButton button;
private JLabel label;
public ChatClient() {
textField.setEditable(false);
messageArea.setEditable(false);
// frame.setSize(500, 500);
// frame.setVisible(true);
frame.getContentPane().add(textField, "South");
frame.getContentPane().add(new JScrollPane(messageArea), "West");
panel = new JPanel();
panel.setBackground(Color.YELLOW);
button = new JButton("Button");
label = new JLabel(new ImageIcon("x.gif"));
panel.add(button);
panel.add(label, BorderLayout.EAST);
frame.add(panel);
frame.pack();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}
private String getServerAddress() {
return JOptionPane.showInputDialog(frame, "Enter IP Address of the Server:",
"Welcome to the Chatter", JOptionPane.QUESTION_MESSAGE);
}
private String getName() {
return JOptionPane.showInputDialog(frame, "Choose a screen name:", "Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 5910);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Thanks in advance,
-Brandon
You can just change your code as below and it will work. Just tested it on my own computer and it worked.
ImageIcon icon = new ImageIcon(getClass().getResource("x.gif"));
label = new JLabel(icon);
It seems your problem is that you didn't actually loaded the image in. Remember to use a ClassLoader to load the resource files.
You should place 'x.gif' under your project directory or your resource folder(preferred) in order to make this work.
For more details about loading resources, take a look at this link.
If the image is in your projects root directory,then you can access it the directly,similar to what you have done.
If it is inside some folder(say resources folder) in your project structure you need to use getClass().getResource("/resources/x.gif").
You can also create a scaled version of the image,specifying the height and width.It can be done using the sample code below:
ImageIcon icon = new ImageIcon("x.gif");
Image img = icon.getImage();
Image newimg = img.getScaledInstance(30, 20,
java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
label = new JLabel(icon);
I am still pretty new to Java and for my class, we have to make a web browser without JEditor. I just need to figure out how to use the socket when a user types in the JTextField and then make it go to that website. Also, I am only supposed to use http:// not https:// if that makes a difference. Anything helps! Thanks!
import javax.swing.*;
import java.awt.*;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.*;
public class WebPanel extends JPanel{
PrintWriter pw;
JTextField text = new JTextField("http://www.");
public WebPanel(){
//trying to connect to the website
try {
Socket s = new Socket(text, 80); //<<<---where the error is thrown
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
//set layout
setLayout(null);
ButtonHandler bh = new ButtonHandler();
text.addActionListener(bh);
text.setBounds(185, 10, 315, 25);
add(text);
//buttons
JButton goButton = new JButton("GO");
goButton.addActionListener(bh);
add(goButton);
goButton.setBounds(500, 10, 75, 25);
JButton backButton = new JButton("BACK");
backButton.addActionListener(bh);
add(backButton);
backButton.setBounds(2, 10, 75, 25);
JButton forwardButton = new JButton("FORWARD");
forwardButton.addActionListener(bh);
add(forwardButton);
forwardButton.setBounds(80, 10, 100, 25);
}
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//buttons for later
if(e.getActionCommand().equals("GO")){
String input = text.getText();
System.out.println("You searched for: " + input);
pw.flush();
}else if(e.getActionCommand().equals("BACK")){
System.out.println("you pressed the back button");
pw.flush();
} else if(e.getActionCommand().equals("FORWARD")){
System.out.println("You pressed the forward button");
pw.flush();
}
}
}
}
}
For simple cases you don't need to use Sockets. You can use URL class like this:
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class URLReadTest {
public static void main(String[] args) throws Exception {
InputStream is = new URL("http://stackoverflow.com/").openStream();
String html = IOUtils.toString(is);
is.close();
System.out.println(html); // Parse HTML here
}
}
And then you have to parse returned HTML by yourself before you can visualize it of course.
i don't know how to change frame's title when an drag and drop event takes place. I 've read Java Docs about DnD and Transferable but i can't find a solution, i've come to an conclusion that i have to play games with DropTargetListener, but i am to a deadlock.Any answer would be a relief!(also in drag n drop i would like to hold the attributes of the text)
The SSCCE is:
package sscceeditor;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.BadLocationException;
import rtf.AdvancedRTFDocument;
import rtf.AdvancedRTFEditorKit;
class ExampleFrame extends JFrame{
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadItem = new JMenuItem("Load");
private JTextPane txtPane = new JTextPane(new AdvancedRTFDocument());
private JScrollPane scroller = new JScrollPane(txtPane);
private JFileChooser chooser = new JFileChooser();
private AdvancedRTFEditorKit rtfKit = new AdvancedRTFEditorKit();
//ctor begins...
public ExampleFrame(){
super("Example Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 400);
this.setLocationRelativeTo(null);
saveItem.addActionListener(new SaveHandler());
loadItem.addActionListener(new LoadHandler());
this.addDragAndDropSupportToJTextPane(txtPane);
//set the kit...
txtPane.setEditorKit(rtfKit);
//create the menu...
fileMenu.add(saveItem);
fileMenu.add(loadItem);
bar.add(fileMenu);
this.setJMenuBar(bar);
//create the main panel...
JPanel mainPane = new JPanel();
mainPane.setLayout(new BorderLayout());
mainPane.add(BorderLayout.CENTER , scroller);
this.setContentPane(mainPane);
}//end of ctor.
//inner event handler classes...
class SaveHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showSaveDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
try(BufferedWriter bw = new BufferedWriter(
new FileWriter(chooser.getSelectedFile().getPath())))
{
rtfKit.write(bw, txtPane.getDocument(), 0, txtPane.getDocument().getLength());
bw.close();
JOptionPane.showMessageDialog( ExampleFrame.this,"Saved");
txtPane.setText("");
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
class LoadHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showOpenDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
StringBuilder sb = new StringBuilder();
try(BufferedReader bw = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath())))
{
txtPane.setText("");
rtfKit.read(bw, txtPane.getDocument(), 0);
bw.close();
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
private void addDragAndDropSupportToJTextPane(JTextPane thePane){
thePane.setDragEnabled(true);
thePane.setDropMode(DropMode.INSERT);
}//end of method.
}//end of class ExampleFrame.
public class SSCCEeditor {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new ExampleFrame().setVisible(true);
}
});
}
}
Thanks a lot for your time!
Here is my main class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;
public class FTP {
public static void main (String []args)
{
Runnable runner = new Runnable(){
public void run()
{
LookAndFeel nimbusLook = new LookAndFeel();
nimbusLook.NimbusLookAndFeel();
JFrame frame = new JFrame("BNA FTP Diagnose");
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(540, 420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
final JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
JMenu helpMenu = new JMenu("Help");
menuBar.add(new JPanel());
menuBar.add(helpMenu);
final JMenuItem aboutMenuItem = new JMenuItem("About");
helpMenu.add(aboutMenuItem);
JPanel titlePanel = new JPanel(new BorderLayout());
frame.add(titlePanel, BorderLayout.NORTH);
JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
titleLabel.setFont(new Font(null, Font.BOLD, 14));
titleLabel.setForeground(Color.BLUE);
titlePanel.add(titleLabel);
JPanel gridPanel = new JPanel(new GridLayout(1, 1));
frame.add(gridPanel);
JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
gridPanel.add(vendorPanel);
final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson",
"BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company",
"Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
final JComboBox vendorList = new JComboBox(vendor);
vendorPanel.add(vendorList);
JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
gridPanel.add(diagnoseButtonPanel);
final JButton diagnoseButton = new JButton("Diagnose");
diagnoseButtonPanel.add(diagnoseButton);
JPanel centerPanel = new JPanel(new BorderLayout());
frame.add(centerPanel, BorderLayout.SOUTH);
JPanel commandPanel = new JPanel(new GridLayout(1, 0));
centerPanel.add(commandPanel);
final JTextArea commandResultArea = new JTextArea(7, 0);
JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
commandPanel.add(scroll);
commandResultArea.setEditable(false);
ActionListener buttonListener = new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
int selectedIndex = vendorList.getSelectedIndex();
String llesiant = "ftp.llesiant.com";
String wkCCH = "FTP1.cch.com";
String proquest = "ftp.proquest.com";
String notes = "notes5.bna.com";
//String lineThree = null;
CommandClass readCommand = new CommandClass();
if (selectedIndex == 0)
{
commandResultArea.setText(readCommand.getCommand(llesiant)); //these return strings
}
else if (selectedIndex == 1)
{
commandResultArea.setText(readCommand.getCommand(wkCCH));
}
else if (selectedIndex == 2)
{
commandResultArea.setText(readCommand.getCommand(proquest));
}
else if (selectedIndex == 3)
{
commandResultArea.setText(readCommand.getCommand(notes));
}
}
};
diagnoseButton.addActionListener(buttonListener);
ActionListener exitListener = new ActionListener (){
public void actionPerformed(ActionEvent el)
{
if (el.getSource()== exitMenuItem)
{
JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
System.exit(0);
}
}
};
exitMenuItem.addActionListener(exitListener);
ActionListener aboutListener = new ActionListener()
{
public void actionPerformed(ActionEvent al)
{
if (al.getSource()== aboutMenuItem)
{
JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");
}
}
};
aboutMenuItem.addActionListener(aboutListener);
}
};
EventQueue.invokeLater(runner);
}
}
Here is my Look and feel class:
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class LookAndFeel {
public void NimbusLookAndFeel()
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
}
}
Here is my CommandClass:
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class CommandClass {
public String getCommand(String ftpSite){
String command = "ftp ";
StringBuffer output = new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(command +ftpSite);
InputStreamReader ir = new InputStreamReader (p.getInputStream());
int outputChar = 0;
while((outputChar = ir.read()) != -1){
output.append((char)outputChar);
if(!ir.ready()){ // If the next read is not guarenteed, come out of loop.
break;
}
}
ir.close();
JOptionPane.showMessageDialog(null, "FTP is connected");
}catch (IOException e){
e.printStackTrace();
}
return output.toString();
}
}
I have this FTP GUI which suppose to connect to an FTP site and return the status. If it's connected it shows the connection prompt.
I got the JTextArea to show the message when the FTP connection is established, but when it's not connected to the ftp site such as my 4th ftp site which is notes5.bna.com it freezes the program. Also a small problem is if you have the program FTP to a site like this "shlfsdklaflkhasdlhfas". It returns the ftp site is not found only after the JOptionPane shows that FTP is connected. I am not sure what's wrong with it.
The reason that notes5.bna.com is freezing is that the site is not responding to FTP connection requests. As you are simply using Runtime#exec to make the connection, this will block indefinitely for a response. Consider using a 3rd party FTP client such as Apache FTPClient which allows you to specify a connection timeout.
A related issue is that some sites are requesting a username & password for access. Again FTPClient allows you to provide login details.
Last but not least, don't let heavyweight non-UI tasks freeze your Swing application. Swing has mechanisms to deal with these such as SwingWorker objects.
Related Swingworker Network Example