小宝--读书笔记
zieckey
全部博文(176)
PHP(1)
Class Design Pri(5)
Design Patterns(21)
Arithmetic Data (21)
职业生涯(1)
其它(0)
音乐电影(0)
生活(1)
修身养性(0)
搞笑(1)
OpenGL(6)
gcc-gdb(2)
socket-net(12)
进程控制(1)
pthread(11)
E680(3)
Win32 C/C++(3)
Standard C/C++(35)
Linux C/C++(15)
QT Embedded(0)
Command(6)
Kernel(1)
Solaris(0)
Other(0)
Install && Usage(0)
Soft Install && (2)
J2EE(2)
J2SE(5)
J2ME(5)
2012年(1)
2011年(4)
2010年(14)
2009年(71)
2008年(103)
Tay_linu
北国飘雪
zouyoupe
zhbnx
妤傛ê鍋
wb123456
dnybz
wanfengc
毋纵年华
aoxuestu
cynthia
Bsolar
王Wangmy
along819
分类: Java
2008-11-07 11:01:34
import java.net.*; public class UDPServer { private static final int PORT = 5000; private DatagramSocket dataSocket; private DatagramPacket dataPacket; private byte receiveByte[]; private String receiveStr; public UDPServer() { Init(); } public void Init() { try { dataSocket = new DatagramSocket(PORT); receiveByte = new byte[1024]; dataPacket = new DatagramPacket(receiveByte, receiveByte.length); receiveStr = ""; int i = 0; while (i == 0)// 无数据,则循环 { dataSocket.receive(dataPacket); i = dataPacket.getLength(); // 接收数据 if (i > 0) { // 指定接收到数据的长度,可使接收数据正常显示,开始时很容易忽略这一点 receiveStr = new String(receiveByte, 0, dataPacket.getLength()); System.out.println(receiveStr); i = 0;// 循环接收 } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { new UDPServer(); } }
import java.io.*; import java.net.*; public class UDPClient { private static final int PORT = 4561; private DatagramSocket dataSocket; private DatagramPacket dataPacket; private byte sendDataByte[]; private String sendStr; public UDPClient() { Init(); } public void Init() { try { // 指定端口号,避免与其他应用程序发生冲突 dataSocket = new DatagramSocket(PORT+1); sendDataByte = new byte[1024]; sendStr = "UDP方式发送数据"; sendDataByte = sendStr.getBytes(); dataPacket = new DatagramPacket(sendDataByte, sendDataByte.length, InetAddress.getByName("localhost"), PORT); dataSocket.send(dataPacket); } catch (SocketException se) { se.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } } public static void main(String args[]) { new UDPClient(); } }
上一篇:自定义log4j的Appender(自定义一个UDPAppender)
下一篇:单元测试Junit教程
登录 注册