[SOLVED] "Threading" a method?
I am trying my hands at socket programming but I am kind of stuck. I am not sure how to implement multi-threading in java. I have a method call listen which I would like to run on a separate thread so that it will not freeze the GUI while it waits. The class is below, and any help is greatly appreciated.
Code:
import java.io.*;
import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.util.Date;
import java.awt.event.*;
public class ChatServer extends JFrame implements ActionListener {
/**
* @param args
*/
// Variables
TextField msg;
TextArea room;
JButton listen;
PrintStream os;
DataInputStream is;
Socket clientSocket;
ServerSocket server;
public ChatServer() {
server = null;
clientSocket = null;
msg = new TextField();
room = new TextArea();
listen = new JButton("Listen");
this.add("South", msg);
this.add("Center", room);
this.add("North", listen);
listen.addActionListener(this);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
if (server != null) {
server.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
room.append(e1.getMessage());
}
System.exit(0);
}
});
}
public static void main(String[] args) {
ChatServer f = new ChatServer();
f.setBounds(0, 0, 250, 200);
f.setTitle("Chat Server");
f.setVisible(true);
}
public boolean keyDown(Event evt, int key) {
if (key == 10) {
room.append(msg.getText() + "\n");
msg.setText("");
} return super.keyDown(evt, key);
}
public void actionPerformed(ActionEvent e) {
if (e.toString().split(",")[1].substring(4).equals("Listen")) {
try {
server = new ServerSocket(4000);
room.append("Server now listening for client...\n");
this.clientSocket = server.accept();
room.append("Client has connected!\n");
os = new PrintStream(this.clientSocket.getOutputStream());
is = new DataInputStream(this.clientSocket.getInputStream());
this.sendText("Welcome, current login time is :" + new Date());
listen();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
room.append(e2.getMessage());
}
}
}
public void sendText(String message) {
os.println(message);
os.flush();
}
public void listen() {
try {
room.append(is.readLine() + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
room.append(e.getMessage());
System.exit(0);
}
listen();
}
}