嗨,大家好啊!我是寻觅
今天下午,坐着没事做,便到自己的硬盘分区上look look;结果发现以前下载的一个张孝祥老师网络课堂教程;
反正没事做,看看不错代码很简单,于是照着做了一个;就是下面这个东东,呵呵,很好玩的,大家先玩玩先
我会找时间做的。里面该注意的地方还真不少;
代码:
1
import
java.awt.
*
;
2
import
java.awt.event.
*
;
3
import
java.net.
*
;
4
5
public
class
Cat
extends
Frame
{
6
7
List lst
=
new
List(
6
);
8
TextField tfIP
=
new
TextField(
15
);
9
TextField tfData
=
new
TextField(
20
);
10
DatagramSocket ds
=
null
;
11
public
Cat()
{
12
try
{
13
ds
=
new
DatagramSocket(
3000
);
14
}
catch
(Exception e)
{
15
e.printStackTrace();
16
}
17
this
.add(lst,
"
Center
"
);
18
Panel p
=
new
Panel();
19
this
.add(p,
"
South
"
);
20
21
p.setLayout(
new
BorderLayout());
22
23
p.add(tfIP,
"
West
"
);
24
p.add(tfData,
"
East
"
);
25
26
new
Thread(
new
Runnable()
{
27
public
void
run()
{
28
byte
[] buf
=
new
byte
[
1024
];
29
DatagramPacket dp
=
new
DatagramPacket(buf,
1024
);
30
while
(
true
)
{
31
try
{
32
ds.receive(dp);
33
lst.add(
new
String(buf,
0
,dp.getLength())
+
""
+
34
"
from
"
+
dp.getAddress().getHostAddress()
+
"
:
"
+
35
dp.getPort(),
0
);
36
}
catch
(Exception e)
{
37
e.printStackTrace();
38
}
39
}
40
}
41
}
).start();
42
43
tfData.addActionListener(
new
ActionListener()
{
44
public
void
actionPerformed(ActionEvent e)
{
45
46
byte
[] buf;
47
buf
=
tfData.getText().getBytes();
48
try
{
49
DatagramPacket dp
=
new
DatagramPacket(buf,buf.length
50
,InetAddress.getByName(tfIP.getText()),
3000
);
51
ds.send(dp);
52
}
catch
(Exception ex)
{
53
if
(
!
ds.isClosed())
{
54
ex.printStackTrace();
55
}
56
}
57
tfData.setText(
""
);
58
59
}
60
}
);
61
62
addWindowListener(
new
WindowAdapter()
{
63
public
void
windowClosing(WindowEvent e)
{
64
ds.close();
65
dispose();
66
System.exit(
0
);
67
}
68
69
}
);
70
71
}
72
public
static
void
main(String[] args)
{
73
System.out.println(
"
starting chat
"
);
74
Cat mainFrame
=
new
Cat();
75
mainFrame.setSize(
300
,
400
);
76
mainFrame.setTitle(
"
UDP聊天工具
"
);
77
mainFrame.setVisible(
true
);
78
mainFrame.setResizable(
false
);
79
}
80
81
}
82
83
地震让大伙知道:居安思危,才是生存之道。
posted on 2007-03-11 20:37
小寻 阅读(410)
评论(0) 编辑 收藏 所属分类:
j2se/j2ee/j2me