|
UDP 和Tcp
协议
接收端
package com.renxing.r0044_DatapramSockeDemo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class JieShouDemo
{
//接收端
public static void main(String[] args) throws IOException
{
DatagramSocket ds=new DatagramSocket(10000);
byte [] bs=new byte[1024];
DatagramPacket dp=new DatagramPacket(bs,bs.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String text=new String(bs,0,bs.length);
System.out.println(ip+"::"+text);
ds.close();
}
}
发送端
package com.renxing.r0044_DatapramSockeDemo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class FasongDemo
{
//发送端
public static void main(String [] args) throws IOException
{
DatagramSocket ds=new DatagramSocket();
byte [] bs="妈妈: 我感冒了".getBytes();
DatagramPacket dp=new DatagramPacket(bs,bs.length,InetAddress.getByName("192.168.1.103"),10000);
ds.send(dp);
ds.close();
}
} |
|