-
Notifications
You must be signed in to change notification settings - Fork 1
/
ChatUsers.java
91 lines (81 loc) · 2.67 KB
/
ChatUsers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.System.out;
public final class ChatUsers extends JFrame implements ActionListener {
String username;
PrintWriter pw;
BufferedReader br;
JTextArea chatmsg;
JTextField chatip;
JButton send,exit;
Socket chatusers;
public ChatUsers(String uname,String servername) throws Exception {
super(uname);
this.username = uname;
chatusers = new Socket(servername,80);
br = new BufferedReader( new InputStreamReader( chatusers.getInputStream()) ) ;
pw = new PrintWriter(chatusers.getOutputStream(),true);
pw.println(uname);
buildInterface();
new MessagesThread().start();
}
public void buildInterface() {
send = new JButton("Send");
exit = new JButton("Exit");
chatmsg = new JTextArea();
chatmsg.setRows(30);
chatmsg.setColumns(50);
chatmsg.setEditable(false);
chatip = new JTextField(50);
JScrollPane sp = new JScrollPane(chatmsg, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(chatip);
bp.add(send);
bp.add(exit);
bp.setBackground(Color.LIGHT_GRAY);
bp.setName("Kstark Chat Application Using Socket");
add(bp,"North");
send.addActionListener(this);
exit.addActionListener(this);
setSize(500,300);
setVisible(true);
pack();
}
@Override
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == exit ) {
pw.println("end");
System.exit(0);
} else {
pw.println(chatip.getText());
chatip.setText(null);
}
}
public static void main(String ... args) {
String SetUserName = JOptionPane.showInputDialog(null,"Please enter your name :", "Kstark Chat Application",
JOptionPane.PLAIN_MESSAGE);
String servername = "localhost";
try {
new ChatUsers( SetUserName ,servername);
} catch(Exception ex) {
out.println( "Error:" + ex.getMessage());
}
}
class MessagesThread extends Thread {
@Override
public void run() {
String line;
try {
while(true) {
line = br.readLine();
chatmsg.append(line + "\n");
}
} catch(Exception ex) {}
}
}
}