public class UDPserver {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws SocketException, IOException {
// TODO code application logic here
//创建服务器端DatagramSocket,指定端口(大于1024的端口)
DatagramSocket socket = new DatagramSocket(8800);
UDPserverThread thread = null;
DatagramPacket packet = null;
int count = 0;
byte[] data = new byte[1024];
while (true) {
packet = new DatagramPacket(data, data.length);
System.out.println("服务器端等待ing");
//接收客户端发送的数据
socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
thread = new UDPserverThread(socket,packet);
thread.start();
count++;
System.out.println("客户端的数量:" + count);
// InetAddress address = socket.getInetAddress();
// System.out.println("当前客户端的IP:" + address.getHostAddress());
// if(socket!=null)
// socket.close();
}
}
public class UDPserverThread extends Thread {
/**
* 通过多线程实现多用户链接
* @param args the command line arguments
*/
DatagramSocket socket=null;
DatagramPacket packet=null;
public UDPserverThread(DatagramSocket socket,DatagramPacket packet){
this.socket=socket;
//创建数据报,用于接收客户端发送的数据
this.packet=packet;
}
@Override
public void run() {
try {
//接收信息
byte[] data=packet.getData();
//读取数据
String info = new String(data, 0, packet.getLength());
System.out.println("----服务器端---接收客户端消息:" + info);
//响应信息
//定义客户端的地址、端口号、数据
InetAddress address =packet.getAddress();
int port=packet.getPort();
byte[] data2="欢迎你".getBytes();
//创建数据报,包含响应的数据信息
DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);
//响应客户端
socket.send(packet2);
//关闭资源
} catch (SocketException ex) {
Logger.getLogger(UDPserverThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(UDPserverThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class UDPClient {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
//定义服务器的地址、端口号、数据
InetAddress address = InetAddress.getByName("localhost");
int port = 8800;
byte[] data = "用户名:admin;密码:32001".getBytes();
//创建数据报,包含发送的数据信息
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
//创建DatagramSocket对象
DatagramSocket socket = new DatagramSocket();
//向服务器端发送数据报
socket.send(packet);
//接收响应的信息
//创建数据报接收服务器端响应的数据
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
socket.receive(packet2);
String info = new String(data2, 0, packet2.getLength());
System.out.println("----客户端---接收服务器端消息:" + info);
socket.close();
}
}
在服务器端中我打算模仿TCP获取客户端的IP,但是那几句不注释掉(就是一开始socket.getInetAddress那里4行)就会出现nullpointerException,没有获取到IP地址,请问是什么原因呢?除了这几行之外都能正常运行的
好吧,把socket换成packet就可以了,我对象理解错了
还有服务器端的socket不能关闭