InetAddress概述:
java.net.InetAddress类:
用于获取IP地址对象;
getLocalHost():获取本机的InetAddress对象
getByName(string):根据主机名或IP的地址值获取主机的InetAddress对象
getLoopbackAddress():获取回环地址的
getHostAddress()返回IP地址字符串
getHostName()获取此IP地址的主机名
UDP协议发送数据:
DatagramSocket()创建对象随机分配端口号
TCP发送方法:
代码演示:
public class 课题02 { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(); String s = "00"; byte[] bys = s.getBytes(); int length = bys.length; InetAddress ip = InetAddress.getByName("An_140"); System.out.println(ip); int port = 2000;// 定义端口 DatagramPacket dp = new DatagramPacket(bys, length, ip, port);// 打包方法 ds.send(dp); ds.close(); }} TCP接收方法: 方法演示:
public class 课题03 {
public static void main(String[] args) throws IOException {
byte[] byt = new byte[1024];
DatagramSocket ds = new DatagramSocket(2000);//端口号
DatagramPacket dp = new DatagramPacket(byt, byt.length);
ds.receive(dp);
InetAddress in = dp.getAddress();
byte[] byt1 = dp.getData();
int length = dp.getLength();
System.out.println("sender ---> " + in.getHostAddress());
System.out.println(new String(byt1, 0, length));
ds.close();
}
}
UDP发送方法:
代码演示:
public class 课题04 { public static void main(String[] args) throws IOException, IOException { Socket sk = new Socket(InetAddress.getByName("MingY-PC"), 10086); OutputStream os = sk.getOutputStream(); os.write("你好!".getBytes()); sk.close(); }}
UDP发送方法:
代码演示:
public class 课题05 { public static void main(String[] args) throws IOException { ServerSocket ssk = new ServerSocket(1086); Socket sk = ssk.accept(); InputStream is = sk.getInputStream(); byte[] byt = new byte[1024]; int x = is.read(byt); String string = new String(byt, 0, x); System.out.println(string);//打印传输的内容; InetAddress ia = sk.getLocalAddress(); System.out.println(ia);//对面计算机域名 is.close(); }}class A implements Runnable { public void run() { }}
//必须有服务端接收;