java使用UDP来进行客户端和服务器端通信的简单例子

1:客户端程序

viewplain

packagecom.pb.udp;

importjava.io.ioexception;

importjava.net.datagrampacket;

importjava.net.inetaddress;

importjava.net.unknownhostexception;

importjava.net.datagramsocket;

/**

*使用sender类来代表客户端程序,

*@authorccna_zhang

*

*/

publicclasssender{

publicstaticvoidmain(string[]args){

stringmsg="hello,world";

byte[]buf=msg.getbytes();

try{

inetaddressaddress=inetaddress.getbyname("192.168.1.80");//服务器地址

intport=8080;//服务器的端口号

//创建发送方的数据报信息

datagrampacketdatagrampacket=newdatagrampacket(buf,buf.length,address,port);

datagramsocketsocket=newdatagramsocket();//创建套接字

socket.send(datagrampacket);//通过套接字发送数据

//接收服务器反馈数据

byte[]backbuf=newbyte[1024];

datagrampacketbackpacket=newdatagrampacket(backbuf,backbuf.length);

socket.receive(backpacket);//接收返回数据

stringbackmsg=newstring(backbuf,0,backpacket.getlength());

system.out.println("服务器返回的数据为:"+backmsg);

socket.close();

}catch(unknownhostexceptione){

e.printstacktrace();

}catch(ioexceptione){

e.printstacktrace();

}

}

}

2:服务器端程序

viewplain

packagecom.pb.udp;

importjava.io.ioexception;

importjava.net.datagrampacket;

importjava.net.datagramsocket;

importjava.net.inetaddress;

importjava.net.socketaddress;

importjava.net.unknownhostexception;

/**

*服务器端程序

*@authorccna_zhang

*

*/

publicclassreceiver{

publicstaticvoidmain(string[]args){

try{

inetaddressaddress=inetaddress.getlocalhost();

intport=8080;

//创建datagramsocket对象

datagramsocketsocket=newdatagramsocket(port,address);

byte[]buf=newbyte[1024];//定义byte数组

datagrampacketpacket=newdatagrampacket(buf,buf.length);//创建datagrampacket对象

socket.receive(packet);//通过套接字接收数据

stringgetmsg=newstring(buf,0,packet.getlength());

system.out.println("客户端发送的数据为:"+getmsg);

//从服务器返回给客户端数据

inetaddressclientaddress=packet.getaddress();//获得客户端的ip地址

intclientport=packet.getport();//获得客户端的端口号

socketaddresssendaddress=packet.getsocketaddress();

stringfeedback="received";

byte[]backbuf=feedback.getbytes();

datagrampacketsendpacket=newdatagrampacket(backbuf,backbuf.length,sendaddress);//封装返回给客户端的数据

socket.send(sendpacket);//通过套接字反馈服务器数据

socket.close();//关闭套接字

}catch(unknownhostexceptione){

e.printstacktrace();

}catch(ioexceptione){

e.printstacktrace();

}

}

}

3:程序运行结果

服务器端:

客户端发送的数据为:hello,world

客户端:

服务器返回的数据为:received

相关推荐