java udp 局域网
两台电脑ip分别为
192.168.1.10
192.168.1.11
192.168.1.10 为服务端执行如下代码
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();
}
}
192.168.1.11 为客户端执行如下代码
public class UDPClient {
private static final int PORT = 5001;
private DatagramSocket dataSocket;
private DatagramPacket dataPacket;
private byte sendDataByte[];
private String sendStr;
public UDPClient() {
Init();
}
public void Init() {
try {
// 指定端口号,避免与其他应用程序发生冲突
dataSocket = new DatagramSocket(PORT+1,InetAddress.getByName("192.168.1.10"));
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();
}
}
服务端建立成功 没报错
客户端发送udp请求失败
报错如下
java.net.BindException: Cannot assign requested address: Cannot bind
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.net.PlainDatagramSocketImpl.bind(Unknown Source)
at java.net.DatagramSocket.bind(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at udptest.UDPClient.Init(UDPClient.java:21)
at udptest.UDPClient.<init>(UDPClient.java:14)
at udptest.UDPClient.main(UDPClient.java:36)
------解决方案--------------------
你请求的端口 不对,应该是服务器的那个端口。
请教:怎么知道一个字符的ASC码