java 利用UDP协议 通信

package udp;
import java.net.* ;
public class UdpTest
{
public static void main(String []args)
{
if (args.length > 0)
runServer();
else
runClient() ;
}
static public void runServer() //服务器端
{
try
{
DatagramSocket ss = new DatagramSocket(6666); //创建数据包套接字
byte date[]=new byte[100];
while(true)
{
DatagramPacket dp=new DatagramPacket (date,100) ; //创建数据包
ss.receive(dp);
System.out.println(new String(date,0,dp.getLength())); //将受到的数据写入
String str="welcome you";
DatagramPacket dp1=new DatagramPacket(str.getBytes(),str.length(),dp.getAddress(),dp.getPort());
ss.send(dp1);
}

}
catch(Exception e)
{
e.printStackTrace();
}


}
static public void runClient() //客户端
{
try{
DatagramSocket ss = new DatagramSocket(); //创建数据包套接字
String str="hello i am zhangsan !";
DatagramPacket p=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("LocalHost"),6666);
ss.send(p);
byte ch[]=new byte[100];
DatagramPacket p1=new DatagramPacket(ch,100) ;
ss.receive(p1);
System.out.println(new String(ch,0,p1.getLength()));
ss.close();
}
catch(Exception e)
{
e.printStackTrace();
}


}


}

你可能感兴趣的:(java)