The following code shows you how to make a simple chat client which can be connected to LAN chat server.
Code
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class ChatClient extends JFrame
implements ActionListener {
Socket s;
JTextField textMsg;
JButton btnSend;
List list;
Container con;
String msg,sendMsg;
PrintWriter pw;
public ChatClient () {
try
{
createComponents();
s = new Socket("192.168.103.44",333);
getMessage();
list.addItem(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
//This function reads message that is sent by server
public void getMessage(){
try
{
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
msg = br.readLine();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//GUI
public void createComponents() {
btnSend = new JButton("Send");
list = new List();
textMsg = new JTextField();
con = getContentPane();
con.setLayout(new BorderLayout());
con.add(list,"Center");
con.add(btnSend,"East");
con.add(textMsg,"South");
setTitle("Client");
setVisible(true);
setSize(400,400);
setResizable(false);
btnSend.addActionListener(this);
//Checking if user pressed "Enter Key"
textMsg.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke){
try
{
if ( ke.getKeyCode() == KeyEvent.VK_ENTER ) {
msg = textMsg.getText();
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os,true);
pw.println(msg);
list.addItem("Client Says : " + msg);
textMsg.setText("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//If send button is pressed
public void actionPerformed(ActionEvent e) {
try
{
if ( e.getSource().equals(btnSend) ) {
//Sending message
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os,true); //true means to auto flush the stream
pw.println(textMsg.getText());
list.addItem("Client Says : " + textMsg.getText());
textMsg.setText("");
}
} catch ( Exception ex ) {
}
}
public static void main(String[] args) {
ChatClient cc = new ChatClient();
}
}
0 comments:
Post a Comment