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
101
102
103
104
105
106
107
| import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient extends Frame
{
/**
*
*/
private String ip="192.168.137.1";
private static final long serialVersionUID = 1L;
TextArea ta = new TextArea();
TextField tf = new TextField();
public void launchFrame() throws Exception
{
this.add(ta, BorderLayout.CENTER);
this.add(tf, BorderLayout.SOUTH);
tf.setText("客户端:");
tf.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try {
String sSend = tf.getText();
if(sSend.trim().length() == 0) return;
ChatClient.this.send(sSend);
tf.setText("客户端:");
ta.append(sSend + "\n");
}
catch (Exception e) { e.printStackTrace(); }
}
}
);
this.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
setBounds(300,300,300,400);
setVisible(true);
tf.requestFocus();
}
Socket s = null;
public ChatClient() throws Exception
{
s = new Socket(ip, 8888);
launchFrame();
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception
{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception
{
s.close();
}
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader (
new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while(str != null && str.length() != 0)
{
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable
{
public void run()
{
if(s == null) return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0)
{
//System.out.println(str);
ChatClient.this.ta.append(str + "\n");
str = dis.readUTF();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
|