//省略了引包
public?class?UDPServer?{
public?static?void?main(String[]?args)?throws?Exception?{
int?count=0;
//?創(chuàng)建服務(wù)器端DatagramSocket,指定端口
DatagramSocket?socket=new?DatagramSocket(8800);
//?創(chuàng)建數(shù)據(jù)報(bào),用于接受客戶端發(fā)送的數(shù)據(jù),客戶端發(fā)送的信息存儲(chǔ)在packet里
byte[]?data=new?byte[1024];//創(chuàng)建字節(jié)數(shù)組,指定接受的數(shù)據(jù)包的大小
DatagramPacket?packet=new?DatagramPacket(data,?data.length);
System.out.println("Server?is?ready");
while(true)
{
//等待接受數(shù)據(jù)
socket.receive(packet);
//啟動(dòng)線程
UDPServerThread?udp=new?UDPServerThread(socket,packet);
Thread?t=new?Thread(udp);
t.start();
count++;
System.out.println("歷史連接數(shù):"+count);
}
}
}
public?class?UDPServerThread?implements?Runnable?{
DatagramSocket?socket=null;
DatagramPacket?packet=null;
//構(gòu)造方法
public?UDPServerThread(DatagramSocket?socket,DatagramPacket?packet)
{
this.socket=socket;
this.packet=packet;
}
@Override
public?void?run(){
/*
*?接受數(shù)據(jù)
*/ ???????
//?讀取數(shù)據(jù)
String?info=new?String(packet.getData(),?0,?packet.getLength());
System.out.println("我是服務(wù)器,客戶端說(shuō):"+info);
/*
*?發(fā)送數(shù)據(jù)
*/
//定義客戶端地址和端口,以及要發(fā)送的信息
InetAddress?address=packet.getAddress();
int?port=packet.getPort();
byte[]?data2="歡迎您!".getBytes();
//創(chuàng)建數(shù)據(jù)報(bào)
DatagramPacket?packet2=new?DatagramPacket(data2,?data2.length,?address,?port);
//發(fā)送信息
try?{
socket.send(packet2);
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}finally{
???socket.close();
}
}
}
public?class?UDPClient?{
public?static?void?main(String[]?args)?throws?Exception??{
/*
*?發(fā)送信息給服務(wù)器
*/
DatagramPacket?packet=null;
DatagramSocket?socket=null;
//1.定義服務(wù)器地址,端口號(hào),數(shù)據(jù)
InetAddress?address=InetAddress.getByName("localhost");
int?port=8800;
byte[]?data="用戶名:admin;密碼:123".getBytes();
//2.創(chuàng)建數(shù)據(jù)報(bào)
packet=new?DatagramPacket(data,?data.length,address,port);
//3.創(chuàng)建DatagramSocket對(duì)象
socket=new?DatagramSocket();
//4.向服務(wù)器發(fā)送數(shù)據(jù)
socket.send(packet);
/*
*?接受服務(wù)器信息
*/
//1.創(chuàng)建數(shù)據(jù)報(bào),用于接受服務(wù)器端響應(yīng)的數(shù)據(jù)
byte[]?data2=new?byte[1024];
DatagramPacket?packet2=new?DatagramPacket(data2,?data2.length);
//2.接受數(shù)據(jù)并輸出
socket.receive(packet2);
String?reply=new?String(data2,?0,?packet2.getLength());
System.out.println("我是客戶端,服務(wù)器返回信息是:"+reply);
//3.關(guān)閉資源
socket.close();
}
}
//這樣的代碼有什么問(wèn)題嗎?運(yùn)行服務(wù)器端后,再運(yùn)行幾次客戶端就會(huì)報(bào)錯(cuò)異常信息是:Exception in thread "main" java.net.SocketException: socket closed
添加回答
舉報(bào)
0/150
提交
取消