package com.socket.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class DataGramServer {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(7777);
byte[] data = new byte[1024];
DatagramPacket dp = new DatagramPacket(data, data.length);
ds.receive(dp);
String msg = new String(dp.getData());
System.out.println(msg);
ds.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*********************************************************************************************************************
package com.socket.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class DataGramClient {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
String msg = "hello world i cs dota wow";
byte[] data = msg.getBytes();
InetAddress add = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(data, data.length,add,7777);
ds.send(dp);
ds.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据报的服务器客户机连接
本文展示了Java中使用UDP进行网络通信的基本概念,包括UDP服务器端和客户端的实现,通过实例代码演示了如何接收和发送数据包。

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



