I'm writing a simply chat client and am moving it over to a nice GUI. The constructor for the server side (client side is android) contains a list that's in the JFrame, and the first part of the server runs, but then the entire frame locks up. Does anyone see the issue? Sorry for the relatively disorganized, not cleanly commented code...
Server:
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ChatServer {
private final int CHAT_PORT = 4453;
ServerSocket sSocket;
Socket cSocket;
PrintWriter pWriter;
BufferedReader bReader;
InetAddress localAddr;
List messageList;
public ChatServer(List entList)
{
messageList = entList;
}
public synchronized void run()
{
messageList.add("Chat Server Starting...");
try {
localAddr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
messageList.add("InnetAddress error");
}
while(true)
{
try {
sSocket = new ServerSocket(CHAT_PORT);
sSocket.setReuseAddress(true);
messageList.add("Server has IP:" + localAddr.getHostAddress());
messageList.add("Server has hostname:" + localAddr.getHostName());
messageList.add("Server has port:" + CHAT_PORT);
} catch (IOException e) {
//ERRORS
if(cSocket.isConnected())
{
messageList.add("User disconnected\n");
try {
cSocket.close();
} catch (IOException e1) {
messageList.add("Error closing client socket");
}
}
else
{
messageList.add("ERROR CREATING SOCKET\n");
}
}
try {
cSocket = sSocket.accept();
cSocket.setReuseAddress(true);
messageList.add("INFO: socket connected");
} catch (IOException e) {
messageList.add("Client Socket Error");
System.exit(-1);
}
try {
pWriter = new PrintWriter(cSocket.getOutputStream(), true);
messageList.add("INFO: Print writer opened");
} catch (IOException e) {
messageList.add("PrintWriter error");
}
try {
bReader = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
messageList.add("INFO: buffered reader opened");
} catch (IOException e) {
messageList.add("BufferedReader error");
}
String inputLine;
try {
while((inputLine = bReader.readLine()) != null)
{
messageList.add(inputLine);
if(inputLine.equals("close"))
{
close();
}
}
} catch (IOException e) {
messageList.add("Buffered Reader error");
}
}
}
public synchronized void close()
{
messageList.add("****Server closing****");
try {
sSocket.close();
} catch (IOException e) {
messageList.add("Error closing server socket");
}
try {
cSocket.close();
} catch (IOException e) {
messageList.add("Error closing client socket");
}
pWriter.close();
try {
bReader.close();
} catch (IOException e) {
messageList.add("Error closing buffered reader");
}
messageList.add("****It's been fun, but I've got to go.****\n****Server has shut down.****");
System.exit(0);
}
}
GUI:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.List;
import java.awt.Toolkit;
#SuppressWarnings("serial")
public class ClientGUI extends JFrame {
private JPanel contentPane;
private JTextField txtEnterTextHere;
private JMenuBar menuBar;
private List messageList;
private JMenu mnOptions;
private JMenu mnHelp;
private JMenuItem mntmStartServer;
private JMenuItem mntmStopServer;
private JMenuItem mntmConnectionInfo;
private JMenuItem mntmEmailDeveloper;
private static String userName;
private ChatServer cServer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientGUI frame = new ClientGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ClientGUI() {
setTitle("Ben's Chat Client");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");
}
});
mnFile.add(mntmExit);
mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
mntmStartServer = new JMenuItem("Start Server");
mntmStartServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ChatServer cServer = new ChatServer(messageList);
cServer.run();
}
});
mnOptions.add(mntmStartServer);
mntmStopServer = new JMenuItem("Stop Server");
mnOptions.add(mntmStopServer);
mntmConnectionInfo = new JMenuItem("Connection Info");
mnOptions.add(mntmConnectionInfo);
mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mntmEmailDeveloper = new JMenuItem("Email Developer");
mnHelp.add(mntmEmailDeveloper);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtEnterTextHere = new JTextField();
txtEnterTextHere.setBounds(10, 220, 334, 20);
txtEnterTextHere.setText("Enter text here...");
contentPane.add(txtEnterTextHere);
txtEnterTextHere.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
messageList.add(userName + ": " + txtEnterTextHere.getText().toString());
}
});
messageList = new List();
btnSend.setBounds(349, 219, 85, 23);
contentPane.add(btnSend);
messageList.setBounds(10, 10, 424, 204);
contentPane.add(messageList);
}
public static String getUsername()
{
return userName;
}
public static void setUsername(String entName)
{
userName = entName;
}
}
Thanks!
It looks like you're starting the server on the Swing thread (see: The Event Dispatch Thread). As soon as you call cServer.run(); in the ActionListener, you are blocking the EDT from doing anything else (such as updating your JFrame and responding to events). Start your server in a background thread instead:
new Thread(new Runnable()
{
#Override
public void run()
{
// start your server
}
}).start();
Related
I have a server client application working just how I want it locally. I need to get the server online so the client program can be used from different computers. Not sure how to do this. I have my own website that I thought I could just put the Server on in the background.
Is this possible or am I just looking at this the wrong way.
Server.java
package core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ArrayList<ClientHandler> clients = new ArrayList<>();
ServerSocket serverSocket = null;
int clientNum = 1; // keeps track of how many clients were created
// 1. CREATE A NEW SERVERSOCKET
try {
serverSocket = new ServerSocket(4444); // provide MYSERVICE at port
// 4444
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
// 2. LOOP FOREVER - SERVER IS ALWAYS WAITING TO PROVIDE SERVICE!
while (true) {
Socket clientSocket = null;
try {
// 2.1 WAIT FOR CLIENT TO TRY TO CONNECT TO SERVER
System.out.println("Waiting for client " + clientNum + " to connect!");
clientSocket = serverSocket.accept();
clientNum++;
ClientHandler c = new ClientHandler(clientSocket, clients);
clients.add(c);
// 2.2 SPAWN A THREAD TO HANDLE CLIENT REQUEST
Thread t = new Thread(c);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
// 2.3 GO BACK TO WAITING FOR OTHER CLIENTS
// (While the thread that was created handles the connected client's
// request)
} // end while loop
} // end of main method
} // end of class MyServer
class ClientHandler implements Runnable {
Socket s; // this is socket on the server side that connects to the CLIENT
ArrayList<ClientHandler> others;
Scanner in;
PrintWriter out;
ClientHandler(Socket s, ArrayList<ClientHandler> others) throws IOException {
this.s = s;
this.others = others;
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
// 1. USE THE SOCKET TO READ WHAT THE CLIENT IS SENDING
while (true) {
String clientMessage = in.nextLine();
// System.out.println(clientMessage);
new Thread(new Runnable() {
#Override
public void run() {
try (PrintWriter fileWriter = new PrintWriter(new FileOutputStream(new File("chat.txt"), true));) {
fileWriter.println(clientMessage);
fileWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(others.size());
for (ClientHandler c : others) {
// System.out.println(c.toString());
c.sendMessage(clientMessage);
}
}
}).start();
}
}
private void sendMessage(String str) {
out.println(str);
out.flush();
}
} // end of class ClientHandler
ClientSide.java
package core;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class ClientSide extends JFrame {
private JPanel contentPane;
private JTextField textField;
private String name;
private JTextArea textArea;
private Thread serverListener;
private Socket socket;
private Scanner in;
private PrintWriter out;
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// ClientSide frame = new ClientSide();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
/**
* Create the frame.
*
* #throws IOException
*/
public ClientSide(String myName) {
try {
socket = new Socket("localhost", 4444);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
serverListener = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String clientMessage = in.nextLine();
try {
System.out.println("Receiving before dec: " + clientMessage);
clientMessage = Crypto.decrypt(clientMessage, "key");
System.out.println("Receiving after dec: " + clientMessage);
addLine(clientMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
serverListener.start();
name = myName;
setTitle("Client Side");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) topPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(topPanel);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(7);
topPanel.add(textArea);
JPanel bottomPanel = new JPanel();
contentPane.add(bottomPanel);
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel lblMessage = new JLabel("Message");
bottomPanel.add(lblMessage);
textField = new JTextField();
bottomPanel.add(textField);
textField.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// send string/message to server
String clientMessage;
try {
clientMessage = Crypto.encrypt(name + ": > " + textField.getText(), "key");
System.out.println("Sending: " + clientMessage);
out.println(clientMessage);
out.flush();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
bottomPanel.add(btnSend);
}
public void addLine(String text) {
textArea.setText(textArea.getText() + text + "\n");
}
}
Provided your ClientSide class connects with your server applicztion on port 4444, you can do the following:
Package your client as jar file and run on each computer you want to distribute it to.
Ensure, each of those computers have JRE installed.
3 Package your Server module as jar file
You should own your server or have admin right. So you can install Java if not there.
Depending on OS, SSH skill might be required
Ensure PORT 4444 is enabled on your host server. firewall
Get the public IP address of your server and use it in your ClideSide code.
I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same.one clint to server is running good but teo client to server is not running properly one clint communication good but second one client not giving response.
Client Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Clientchatform extends JFrame implements ActionListener {
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
String line;
BufferedReader br;
String response;
BufferedReader is ;
PrintWriter os;
public Clientchatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
Send.addActionListener(this);
conn = new Socket(InetAddress.getLocalHost(), 2000);
ChatHistory.setText("Connected to Server");
this.setTitle("Client");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
br= new BufferedReader(new InputStreamReader(System.in));
String line = is.readLine();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Server:"
+ line);
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "Me:"
+ NewMsg.getText());
try {
br= new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
ChatHistory.append(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
Clientchatform chatForm = new Clientchatform();
}
}
Server Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class serverChatform extends JFrame implements ActionListener {
static ServerSocket server;
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
//DataInputStream dis;
//DataOutputStream dos;
String line;
BufferedReader is ;
public serverChatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
this.setTitle("Server");
Send.addActionListener(this);
server = new ServerSocket(2000, 1, InetAddress.getLocalHost());
ChatHistory.setText("Waiting for Client");
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter os=new PrintWriter(conn.getOutputStream());
line=is.readLine();
ChatHistory.append(ChatHistory.getText() + 'n' + "Client:"
+ line);
} catch (Exception e1)
{
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "ME:"
+ NewMsg.getText());
try {
PrintWriter os =new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
}
You're definitely on the right track, but I've got a question for you to ask yourself.
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
How often is this code executed? Consider that of course the main(),
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
is only called once, and therefore only one serverChatform will ever be created.
As you seem to have written quite a bit of code yourself, and it therefore seems like you're ready to learn more, I'm not going to give a full solution, but merely a direction.
Once you accept a client, with conn = server.accept();, you will have to create another new serverChatform();. This has to happen in a different Thread though. How to do this, I leave as an exercise for you.
Each connected client has to be served in its own thread. Additionally you need a Thread that continiously listens for new clients to connect. That would look like this.
List<Socket> clients; // Save the socket for each client
[...]
new Thread(new Runnable(){
#Override
public void run() {
// Thread that runs forever listening for new clients
while(true){
Socket conn = server.accept();
// new client has connected, store its socket
clients.add(conn);
// and start new thread that interacts with this new client
new Thread(new Runnable(){
#Override
public void run() {
// SERVE CLIENT HERE!
}
}).start();
}
}
}).start();
I am building an application on Socket programming in swing in which server listens for clients and if a client is connected I want
A button should be added for each client if connected on server screen
Add a listener on each button.For example add Send Message function for each client
I have created a thread in server which listens for client connections but I can not add jbutton at runtime.
Please reply.
Is that what you need ? :
import javax.swing.*;
import java.awt.event.*;
public class NewButtonOnRunTime {
static JPanel panel;
static JFrame frame;
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame = new JFrame("Add Buttons");
JButton button = new JButton("Simulate new Client");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JButton jb = new JButton("A new Client");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This is an button action");
}
});
panel.add(jb);
frame.revalidate();
}
});
panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Assuming you already have some kind of isConnected bool,
if(isConnected){
JButton runTimeButton = new JButton();
runTimeButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//do all the things you need to do in here,
//alternatively, define this inner class somewhere else and pass in
// an instance of it
}
});
frame.add(runTimeButton);
}
Based on ServerSocket communication in java (i.e. TCP), if a client is connected to the server with a particular port say 5555, no other clients will not be able to connect to the server with the same port at the same time because the port is already in use. So, each client should be using different port if you want to get simultaneous communication with the clients.
Look at this sample code, it adds JButton at runtime when a new client is connected :
(run client code and server code in separate machine connected together)
Server code
package com.test.socket;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class ServerFrame extends JFrame {
private Map<Integer, SocketVO> serverSocketMap;
private int startingPort = 5555;
public ServerFrame() {
}
public ServerFrame(String title) {
super(title);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setLayout(new FlowLayout());
initComponents();
serverSocketMap = new HashMap<Integer, SocketVO>();
keepStartServerSocket();
setVisible(true);
}
private JTextArea area = null;
private void initComponents() {
area = new JTextArea(20, 20);
add(area);
// addDynamicButton();
}
private void addDynamicButton(final int port) {
JButton button = new JButton("Client on " + port + " port");
add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Socket socket = serverSocketMap.get(port).getSocket();
try {
String content = area.getText();
socket.getOutputStream().write(content.getBytes());
System.out.println("seding text area content to " + port);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class SocketVO {
private ServerSocket serverSocket;
private Socket socket;
public ServerSocket getServerSocket() {
return serverSocket;
}
public void setServerSocket(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
}
private void keepStartServerSocket() {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
System.out.println("waiting for a client at port "
+ startingPort);
openServerSocket(startingPort);
startingPort++;
}
}
}).start();
}
private void openServerSocket(final int port) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
final Socket socket = serverSocket.accept();
SocketVO socketVO = new SocketVO();
socketVO.setServerSocket(serverSocket);
socketVO.setSocket(socket);
serverSocketMap.put(port, socketVO);
addDynamicButton(port);
checkForCosing(port, socket);
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkForCosing(final int port, final Socket socket) {
new Thread(new Runnable() {
#Override
public void run() {
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while ((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
if (builder.toString().equals("close")) {
closeServerSocket(port);
System.out.println("server port " + port + " closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/**
* the method to close corresponding sockets
*
* #param port
*/
private void closeServerSocket(int port) {
Socket socket = serverSocketMap.get(port).getSocket();
ServerSocket serverSocket = serverSocketMap.get(port).getServerSocket();
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerFrame("Server Socket Frame");
}
}
Client code :
package com.test.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private int startingPort = 5550;
private void bindToServer() {
while(true) {
try {
Socket socket = new Socket("127.0.0.1", startingPort);
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
System.out.println("message from server : "+builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
startingPort++;
}
if (startingPort == 5580) {
}
}
}
public static void main(String[] args) {
new Client().bindToServer();
}
}
As per your last comment:
I have tested the program with two clients. The server is connected to two clients successfully. But buttons are not added at runtime for each client.
You are able to connect with multiple client and you have added a button also but it's not visible on the server.
Calling validate() again on JFrame will solve your problem after adding new JButton.
public class Test extends JFrame {
private JButton field[];
public JButton[] getField() {
return field;
}
public void test(int n) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
field = new JButton[n];
for (int i = 0; i < field.length; i++) {
field[i] = new JButton("" + i + "");
field[i].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("clicked button");
}
});
panel.add(field[i]);
}
add(panel);
}
public static void main(String[] args) {
Test test = new Test();
test.setSize(300, 300);
test.setVisible(true);
test.setLocationRelativeTo(null);
test.test(5);
}
}
EDIT: The code now works! Here's how I did it:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
private File workingFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = new ProcessBuilder("bash").directory(workingFolder).start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
int code = bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
if (code == 0 && command.split(" ").length > 1) workingFolder = new File(command.split(" ")[1]);
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
if (lines.length == 0) return;
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
I have been working on a Java terminal application. It works except that it only prints the output of the first command. Here's a picture of the GUI when I try to run ls more than once.
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final Process bash = new ProcessBuilder("/bin/bash").start();
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
A Process object can be used only once, so subsequent calls to Process.waitFor() just immediately return (as the process is already terminated).
Instead you have to request a new Process each time from your ProcessBuilder.
Here is the correct code:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final ProcessBuilder builder = new ProcessBuilder("/bin/bash");
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = builder.start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
Once a process has exited, it can not be "read" from or "written" to.
You're code will also block on the "waitFor" method, meaning that your UI won't be updated until the process has completed running. This is really helpful...
Instead, you need to start the process and allow it to continue running, monitoring the state in the background.
Because Swing is a single threaded environment, you need to be careful about how you handle long running/blocking processes and updates to the UI.
To this end, I've used a SwingWorker to read the output of the Process in a background thread and re-sync the updates back to the Event Dispatching Thread. This allows the UI to continue running and remain responsive while the output from the running process is read in...
Also, instead of "running" a new command each time, creating a new process, you will need to write to the Process's input put stream.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTerminal {
public static void main(String[] args) {
new TestTerminal();
}
public TestTerminal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea output;
private JTextField input;
private Process process;
public TestPane() {
setLayout(new BorderLayout());
output = new JTextArea(20, 20);
input = new JTextField(10);
output.setLineWrap(false);
output.setWrapStyleWord(false);
output.setEditable(false);
output.setFocusable(false);
add(new JScrollPane(output));
add(input, BorderLayout.SOUTH);
input.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = input.getText() + "\n";
input.setText(null);
output.append("\n" + cmd + "\n\n");
if (process == null) {
ProcessBuilder pb = new ProcessBuilder("bash");
pb.directory(new File("."));
try {
process = pb.start();
InputStreamWorker isw = new InputStreamWorker(output, process.getInputStream());
isw.execute();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
new Thread(new Runnable() {
#Override
public void run() {
int exit = -1;
try {
exit = process.waitFor();
} catch (InterruptedException ex) {
}
System.out.println("Exited with " + exit);
input.setEnabled(false);
}
}).start();
}
OutputStream os = process.getOutputStream();
try {
os.write(cmd.getBytes());
os.flush();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
}
});
}
}
public class InputStreamWorker extends SwingWorker<Void, Character> {
private InputStream is;
private JTextArea output;
public InputStreamWorker(JTextArea output, InputStream is) {
this.is = is;
this.output = output;
}
#Override
protected void process(List<Character> chunks) {
StringBuilder sb = new StringBuilder(chunks.size());
for (Character c : chunks) {
sb.append(c);
}
output.append(sb.toString());
}
#Override
protected Void doInBackground() throws Exception {
int in = -1;
while ((in = is.read()) != -1) {
publish((char)in);
}
return null;
}
}
}
I would also recommend that you avoid KeyListener where you can. JTextField utilises a ActionListener, which will be called when ever the user presses the "action" key, what ever that might be for the given platform...
I have written this code to make the computer lab application to monitor the students. Here screen locking is working but disabling keys are not working I tried with robot here
How to run the loops to listen the messages continuously and also check the status of the Screenlocker to make the screen locked/unlocked in Studentchat.java
package org;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
#SuppressWarnings("serial")
public class ScreenLocker extends JWindow implements KeyListener {
private boolean locked;
public ScreenLocker() {
super();
this.locked = false;
JLabel label = new JLabel("Your Screen is Locked by your Teacher", JLabel.CENTER);
label.setFont(new Font("Serif", Font.PLAIN, 30));
JPanel panel =(JPanel) getContentPane();
panel.setBackground(Color.WHITE);
panel.add(label, BorderLayout.CENTER);
setFocusTraversalKeysEnabled(false);
}
public synchronized void setLocked(boolean lock) throws AWTException, InterruptedException {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (lock) {
setAlwaysOnTop(true);
this.setVisible(true);
gd.setFullScreenWindow(this);
this.locked = true;
Robot robot = new Robot();
releaseKeys(robot);
kill("explorer.exe");
kill("taskmgr.exe");
} else {
gd.setFullScreenWindow(null);
this.setVisible(false);
this.locked = false;
restar("taskmgr.exe");
restar("explorer.exe");
this.dispose();
}
}
public boolean isLocked() {
return locked;
}
private void kill(String string) {
try {
Runtime.getRuntime().exec("taskkill /F /IM " + string).waitFor();
} catch (Exception e) {
}
}
private void releaseKeys(Robot robot) {
robot.keyRelease(17);
robot.keyRelease(18);
robot.keyRelease(127);
robot.keyRelease(524);
robot.keyRelease(9);
}
private void restar(String string) {
try {
Runtime.getRuntime().exec(string).waitFor();
} catch (Exception e) {
}
}
#Override
public void keyPressed(KeyEvent e) {
e.consume();
}
#Override
public void keyReleased(KeyEvent e) {
e.consume();
}
#Override
public void keyTyped(KeyEvent e) {
e.consume();
}
}
package org;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class StudentChat extends JFrame implements Runnable
{
private TextField tf = new TextField();
private JTextArea ta = new JTextArea(10,20);
private Socket socket;
private DataOutputStream dout;
private DataInputStream din;
private String cmdmsg = null;
public StudentChat()
{
ta.setLineWrap(true);
ta.setEditable(false);
ta.setForeground(Color.blue);
JScrollPane scp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String host = "192.168.1.235";
int port = 5000;
setLayout( new BorderLayout() );
setSize(400, 200);
setTitle("Student Chat Application");
add( "South", tf );
add( "Center", scp );
tf.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
processMessage( e.getActionCommand() );
}
} );
try
{
socket = new Socket( host, port );
//System.out.println( "connected to "+socket );
ta.append("connected to "+socket.getInetAddress().getHostName()+"\n");
din = new DataInputStream( socket.getInputStream() );
dout = new DataOutputStream( socket.getOutputStream() );
new Thread( this ).start();
} catch( IOException ie ) {}
}
private void processMessage( String message ) {
try {
String user = System.getProperty("user.name");
dout.writeUTF(user+" :"+message);
tf.setText( "" );
} catch( IOException ie ) {}
}
public void run()
{
try
{
while (true)
{
ScreenLocker sl = new ScreenLocker();
String message = din.readUTF();
if(message.equals("Teacher: "+System.getProperty("user.name")+"lock"))
{
sl.setLocked(true);
}
if(message.equals("Teacher: "+System.getProperty("user.name")+"unlock"))
{
sl.setLocked(false);
}
if(message.indexOf('>')>0)
{
cmdmsg = message.substring(0, message.indexOf('>'));
if(cmdmsg.equals("Teacher: "+System.getProperty("user.name")+"cmd"))
{
String cmd = message.substring(message.indexOf('>')+1);
try
{
Runtime.getRuntime().exec(cmd);
}
catch (Exception e) {}
}
}
ta.append( message+"\n" );
}
} catch( IOException ie ) {}
catch (AWTException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
new StudentChat().setVisible(true);
}
}