//这是UdpThread类
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpThread extends Thread{
DatagramSocket socket=null;
DatagramPacket packet=null;
byte[] data=new byte[1024];
public UdpThread(DatagramSocket socket,DatagramPacket packet,byte[] data){
this.socket=socket;
this.packet=packet;
this.data=data;
}
public void run(){
DatagramPacket packet=new DatagramPacket(data, data.length);
String info=new String(data, 0, packet.getLength());
System.out.println("I'm the Server,The Client said:"+info);
InetAddress address=packet.getAddress();
int port =packet.getPort();
byte[] data2="Welcome!!".getBytes();
DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);
try {
socket.send(packet2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.close();
}
}
//这是UdpServer类
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UdpServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket(8080);//实例化DatagramSocket,指定8080端口
byte[] data=new byte[1024];
DatagramPacket packet=new DatagramPacket(data, data.length);
System.out.println("服务器已经启动");
int count=0;
while(true){
socket.receive(packet);
UdpThread thread=new UdpThread(socket,packet,data);
thread.start();
count++;
System.out.println("当前连接的客服端有:"+count+"个。");
}
}
}
//这是UdpClient类
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpClient {
public static void main(String[] args) throws IOException {
InetAddress address=InetAddress.getByName("localhost");
int port=8080;
byte[] data="username:admikn;password:orange".getBytes();//创建地址,端口,字节
DatagramPacket packet=new DatagramPacket(data, data.length, address, port);//实例化DatagramPacket
DatagramSocket socket=new DatagramSocket();//实例化DatagramSocket
socket.send(packet);//发送数据报
byte[] data2=new byte[1024];
DatagramPacket packet2=new DatagramPacket(data2,data2.length);
socket.receive(packet2);
String reply=new String(data2, 0, packet2.getLength());
System.out.println("The server said:"+reply);
socket.close();
}
}
把异常信息贴下呢
吧thread类里面的socket.close()删掉
和我一样的问题……请问您解决了没有?似乎是packet传到线程里的时候就是null了