-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatClient.java
88 lines (87 loc) · 2.63 KB
/
ChatClient.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
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.System.out;
public class ChatClient extends JFrame implements ActionListener
{
String uname,touname;
String servername = "localhost";
PrintWriter pw;
BufferedReader br;
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;
Socket client;
public ChatClient(String uname,String servername) throws Exception
{
super(uname); // set title for frame
this.uname = uname;
client = new Socket(servername,9999);
br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
pw = new PrintWriter(client.getOutputStream(),true);
pw.println(uname); // send name to server
buildInterface();
new MessagesThread().start(); // create thread for listening for messages
}
public void buildInterface()
{
btnSend = new JButton("Send");
btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(tfInput);
bp.add(btnSend);
bp.add(btnExit);
add(bp,"South");
btnSend.addActionListener(this);
btnExit.addActionListener(this);
setSize(500,300);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent evt)
{
if ( evt.getSource() == btnExit ) {
pw.println("end"); // send end to server so that server know about the termination
System.exit(0);
} else {
// send message to server
pw.println(tfInput.getText());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String touname = "";
pw.println(touname);
}
}
public static void main(String [] args)
{
// take username from user
} // end of main
// inner class for Messages Thread
class MessagesThread extends Thread
{
public void run()
{
String line;
try
{
while(true)
{
line = br.readLine();
taMessages.append(line + "\n");
} // end of while
}
catch(Exception ex)
{
}
}
}
} // end of client