-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.java
100 lines (92 loc) · 2.69 KB
/
client.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
92
93
94
95
96
97
98
99
100
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Time;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class client extends JFrame implements ActionListener {
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
public client() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
Send.addActionListener(this);
conn = new Socket("localhost",2000);
Thread t;
t = new Thread();
t.start();
ChatHistory.setText("Connected to Server");
this.setTitle("Client");
while (true) {
try {
DataInputStream dis = new DataInputStream(conn.getInputStream());
String string = dis.readUTF();
ChatHistory.setText(ChatHistory.getText() + '\n' + "Server:"
+ string);
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + '\n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + '\n' + "Me:"
+ NewMsg.getText());
try {
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
dos.writeUTF(NewMsg.getText());
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + '\n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
client chatForm = new client();
}
}