Java UDP网络编程主要通过 DatagramSocket和DatagramPacket 两个类实现的,下面是一个示例程序,
Server监听UDP 2000端口并把收到的Long类型数值打印出来
Client则通过输入获得Long类型的数值,并把它发给Server
Server:

/**//* Coding by nyzhl */
import java.net.*;
import java.io.*;

public class DatagramServer ...{
public static void main (String[] args) ...{
DatagramSocket ds = null;
try ...{
ds = new DatagramSocket(2000);
}
catch (SocketException e) ...{
e.printStackTrace();
System.exit(-1);
}
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
while (true) ...{
DataInputStream in = new DataInputStream (
new ByteArrayInputStream (buffer)
);
try ...{
ds.receive(dp);
System.out.println(in.readLong());
in.close();
}
catch (IOException e) ...{
e.printStackTrace();
continue;
}
}
//ds.close(); JDK提示"无法访问的语句"
//因为前面是死循环,无论如何也执行不到后面的语句
}
}Client:

/**//* coding by nyzhl */
import java.net.*;
import java.io.*;

public class DatagramClient ...{
public static void main (String[] args) ...{
DatagramSocket ds = null;
try ...{
ds = new DatagramSocket();
}
catch (SocketException e) ...{
e.printStackTrace();
System.exit(-1);
}
BufferedReader typeReader = new BufferedReader (
new InputStreamReader(System.in)
);
long data = 0;
while(true) ...{
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream (bytesOut);
try ...{
data = Long.parseLong(typeReader.readLine());
dataOut.writeLong(data);
dataOut.flush();
byte[] buffer = bytesOut.toByteArray();
DatagramPacket dp = new DatagramPacket(
buffer,
buffer.length,
new InetSocketAddress("127.0.0.1",2000)
);
ds.send(dp);
dataOut.close();
bytesOut.close();
}
catch (SocketException e) ...{
System.err.println("Socket Error!");
continue;
}
catch (IOException e) ...{
System.err.println("IO Error!");
continue;
}
catch (Exception e) ...{
e.printStackTrace();
continue;
}
}
//ds.close(); JDK提示"无法访问的语句"
//因为前面是死循环,无论如何也执行不到后面的语句
}
}
下面参看API文档
Class DatagramSocket:
| Constructor Summary | |
|---|---|
| DatagramSocket() Constructs a datagram socket and binds it to any available port on the local host machine. |
protected | DatagramSocket(DatagramSocketImpl impl) Creates an unbound datagram socket with the specified DatagramSocketImpl. |
| DatagramSocket(int port) Constructs a datagram socket and binds it to the specified port on the local host machine. |
| DatagramSocket(int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address. |
| DatagramSocket(SocketAddress bindaddr) Creates a datagram socket, bound to the specified local socket address. |
| Method Summary | |
|---|---|
void | bind(SocketAddress addr) Binds this DatagramSocket to a specific address & port. |
void | close() Closes this datagram socket. |
void | connect(InetAddress address, int port) Connects the socket to a remote address for this socket. |
void | connect(SocketAddress addr) Connects this socket to a remote socket address (IP address + port number). |
void | disconnect() Disconnects the socket. |
boolean | getBroadcast() Tests if SO_BROADCAST is enabled. |
DatagramChannel | getChannel() Returns the unique DatagramChannel object associated with this datagram socket, if any. |
InetAddress | getInetAddress() Returns the address to which this socket is connected. |
InetAddress | getLocalAddress() Gets the local address to which the socket is bound. |
int | getLocalPort() Returns the port number on the local host to which this socket is bound. |
SocketAddress | getLocalSocketAddress() Returns the address of the endpoint this socket is bound to, or null if it is not bound yet. |
int | getPort() Returns the port for this socket. |
int | getReceiveBufferSize() Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket. |
SocketAddress | getRemoteSocketAddress() Returns the address of the endpoint this socket is connected to, or null if it is unconnected. |
boolean | getReuseAddress() Tests if SO_REUSEADDR is enabled. |
int | getSendBufferSize() Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket. |
int | getSoTimeout() Retrieve setting for SO_TIMEOUT. |
int | getTrafficClass() Gets traffic class or type-of-service in the IP datagram header for packets sent from this DatagramSocket. |
boolean | isBound() Returns the binding state of the socket. |
boolean | isClosed() Returns whether the socket is closed or not. |
boolean | isConnected() Returns the connection state of the socket. |
void | receive(DatagramPacket p) Receives a datagram packet from this socket. |
void | send(DatagramPacket p) Sends a datagram packet from this socket. |
void | setBroadcast(boolean on) Enable/disable SO_BROADCAST. |
static void | setDatagramSocketImplFactory(DatagramSocketImplFactory fac) Sets the datagram socket implementation factory for the application. |
void | setReceiveBufferSize(int size) Sets the SO_RCVBUF option to the specified value for this DatagramSocket. |
void | setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option. |
void | setSendBufferSize(int size) Sets the SO_SNDBUF option to the specified value for this DatagramSocket. |
void | setSoTimeout(int timeout) Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. |
void | setTrafficClass(int tc) Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. |
Class DatagramPacket:
| Constructor Summary | |
|---|---|
DatagramPacket(byte[] buf, int length) Constructs a DatagramPacket for receiving packets of length length. | |
DatagramPacket(byte[] buf, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length length to the specified port number on the specified host. | |
DatagramPacket(byte[] buf, int offset, int length) Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer. | |
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length length with offset ioffsetto the specified port number on the specified host. | |
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) Constructs a datagram packet for sending packets of length length with offset ioffsetto the specified port number on the specified host. | |
DatagramPacket(byte[] buf, int length, SocketAddress address) Constructs a datagram packet for sending packets of length length to the specified port number on the specified host. | |
| Method Summary | |
|---|---|
InetAddress | getAddress() Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. |
byte[] | getData() Returns the data buffer. |
int | getLength() Returns the length of the data to be sent or the length of the data received. |
int | getOffset() Returns the offset of the data to be sent or the offset of the data received. |
int | getPort() Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received. |
SocketAddress | getSocketAddress() Gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from. |
void | setAddress(InetAddress iaddr) Sets the IP address of the machine to which this datagram is being sent. |
void | setData(byte[] buf) Set the data buffer for this packet. |
void | setData(byte[] buf, int offset, int length) Set the data buffer for this packet. |
void | setLength(int length) Set the length for this packet. |
void | setPort(int iport) Sets the port number on the remote host to which this datagram is being sent. |
void | setSocketAddress(SocketAddress address) Sets the SocketAddress (usually IP address + port number) of the remote host to which this datagram is being sent. |
本文介绍 Java 中使用 DatagramSocket 和 DatagramPacket 实现 UDP 网络编程的方法。Server 端监听 2000 端口并接收 Long 类型数据,Client 端从标准输入读取 Long 类型数据并发送到 Server。
555

被折叠的 条评论
为什么被折叠?



