Java Chat ProgramI wrote this program very long back when I was learning Java Net and Swing - Can be useful for beginers.It is damn easy to write network programs in Java and thats why I like Java. It is here for you to modify and refine. (The class name is DevilsCry - I gave this name 'cos suddenly thoughts of one guy came to my mind, who was crazy about Devils!- Devil's cry in a PinkFloyd Song.) There are a handful of Bugs in this program.Never tested properly. So it is only for learning, testing and and modifying.
//---------------------------------------------
//DevilsCry.java
//A Chat client with Embedded server on it.
//Ranjith.
//---------------------------------------------
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.event.KeyEvent.*;
import java.io.*;
import java.net.*;
class DevilsCry extends JFrame implements Runnable{
ServerSocket srvrsocket=null; //server socket
Socket clntsocket=null; //client socket
BufferedReader in = null; //in-buffer for server
PrintWriter out = null; //out-buffer for server
BufferedReader clntin = null; //in-buffer for client
PrintWriter clntout = null; //out-buffer for client
final int PORT=4444;
boolean clientconnected = false;
String line;
//-- all UI components
JTextArea msgs; //incoming messages
JTextArea sendmsg; //message to be sent
JLabel status;
JPanel panel;
JMenuBar menuBar;
JMenu mainMenu,editMenu;
JMenuItem miconnect,miexit,miclear;
String connectto="";
char c;
String newtext="";
DevilsCry(String title){ //Constructor..!
createUI();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setTitle(title);
setSize(300,300);
setVisible(true);
}
public void getInput(){
System.out.println("Getting input...");
final JDialog jdlg = new JDialog();
JPanel mPanel = new JPanel();
JLabel label = new JLabel("Comp. Name/IP:");
final JTextField input = new JTextField(20);
JButton okbutton = new JButton("Connect");
mPanel.add(label);
mPanel.add(input);
okbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
connectto = input.getText();
if(connectto != null || !connectto.equals("")){
System.out.println("Host:"+connectto);
try{
if(clntin != null){
clntin.close();
clntout.close();
clntsocket.close();
}
clntsocket = new Socket(connectto, PORT);
clntout = new PrintWriter(clntsocket.getOutputStream(), true);
clntin = new BufferedReader(new InputStreamReader(clntsocket.getInputStream()));
clientconnected = true;
status.setText("Connected to "+connectto);
}
catch(Exception ex){
System.out.println("Blast!");
status.setText("**Not! Connected to "+connectto+"!**");
}
jdlg.dispose();
}
}});
mPanel.add(okbutton);
jdlg.getContentPane().add(mPanel);
jdlg.setSize(250,120);
jdlg.setResizable(false);
jdlg.setVisible(true);
}
public void run(){
try{
srvrsocket = new ServerSocket(PORT);
System.out.print("\nWhat Goes On In Your Heart?");
System.out.println("Server listening.. "+PORT);
}
catch(Exception ex){
System.out.println("Failed Server at "+PORT);
status.setText("Connected to "+connectto+" FAILED!");
}
try{
clntsocket = srvrsocket.accept();
}
catch(Exception ex){
System.out.println("Failed Accept "+ex);
System.exit(-1);
}
listen();
}
public void listen(){ //the server's listening
while(true){
try{
System.out.println("Srvr Accepting...");
line="";
try{
in = new BufferedReader(new InputStreamReader(clntsocket.getInputStream()));
out = new PrintWriter(clntsocket.getOutputStream(), true);
line = in.readLine();
if(line != null){
msgs.append(line+"\n");
msgs.selectAll(); // trick to scroll;)
line ="";
}
}catch (Exception e) {System.out.println("Blast! failed read:"+e); //System.exit(-1);
status.setText("**ERROR:Connection Closed!**");
}
}
catch (Exception e) {
System.out.println("Read failed");
System.exit(-1);
}
}//end while
}
public void createUI(){
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
}
msgs = new JTextArea();
sendmsg = new JTextArea(5,5);
status = new JLabel("Use Main->Connect to Connect");
panel = new JPanel();
panel.setBorder(BorderFactory.createEtchedBorder());
status.setFont(new Font("monospace", Font.PLAIN, 9));
//Scroller for textarea ctl
JScrollPane scroller = new JScrollPane();
JViewport vport = scroller.getViewport();
vport.add(msgs);
msgs.setEditable(false);
msgs.setLineWrap(true);
msgs.setWrapStyleWord(true);
msgs.setFont(new Font("monospace", Font.PLAIN, 11));
sendmsg.setFont(new Font("Courier", Font.PLAIN, 11));
sendmsg.setLineWrap(true);
sendmsg.setWrapStyleWord(true);
sendmsg.addKeyListener( new KeyListener() {
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e){
//all these to get each key and send it! may sux
c = e.getKeyChar(); //get current char
if(c == java.awt.event.KeyEvent.VK_ENTER ){
newtext = new String(sendmsg.getText().trim());
if(clientconnected)
clntout.println("{"+(clntsocket.getLocalAddress()).toString()+" Says} "+newtext);
newtext="";
sendmsg.requestFocus();
sendmsg.setText("");
}
}
public void keyTyped(KeyEvent e){
}
});
JScrollPane scroller1 = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JViewport vport1 = scroller1.getViewport();
vport1.add(sendmsg);
menuBar = new JMenuBar();
mainMenu = new JMenu("Main");
editMenu = new JMenu("Edit");
miconnect = new JMenuItem("Connect");
miexit = new JMenuItem("Exit");
miclear = new JMenuItem("Clear");
miconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getInput();
}});
miexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
miclear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
msgs.setText("");
}});
mainMenu.add(miconnect);
mainMenu.add(miexit);
editMenu.add(miclear);
menuBar.add(mainMenu);
menuBar.add(editMenu);
//Adding ctls into the frame
JPanel northpanel = new JPanel();
JPanel centrpanel = new JPanel();
JPanel southpanel = new JPanel();
northpanel.setLayout(new BorderLayout());
centrpanel.setLayout(new BorderLayout());
southpanel.setLayout(new BorderLayout());
northpanel.add("Center",menuBar);
centrpanel.add("Center",scroller);
southpanel.add("Center",scroller1);
southpanel.add("South",status);
panel.setLayout(new BorderLayout());
panel.add("North", northpanel);
panel.add("Center",centrpanel);
panel.add("South", southpanel);
getContentPane().add(panel);
}
protected void finalize(){ //try clean up
try{
in.close();
out.close();
clntin.close();
clntout.close();
srvrsocket.close();
clntsocket.close();
} catch (IOException e) {
//What to do, anyways exit.
System.exit(-1);
}
}
public static void main(String[] arg){
DevilsCry gui = new DevilsCry("Lo and Behold me Conquering the World!"); //Instantiate
Thread t = new Thread(gui); //Start the thread
t.start();
}
}
|