Socket UDP、TCP 简介

Socket UDP、TCP 简介

1.1 Java 获取 IP、URL

//获取IP
public class IPDemo {
	public static void main(String[] args) throws UnknownHostException {
		//获取本地IP:主机名  / 127.0.0.1  /  localhost
		InetAddress ip=InetAddress.getByName("gudu");
		System.out.println(ip);
		System.out.println(ip.getHostAddress()); //返回IP
		System.out.println(ip.getHostName());    //返回计算机名
		System.out.println(ip.getLocalHost());     //获取本地主机IP
		
		System.out.println("-----------------------获取网络IP------------------------");
		
		InetAddress baiduIP=InetAddress.getByName("www.baidu.com");
		System.out.println(baiduIP);
	}

}
//获取url
public class URLDemo {
	public static void main(String[] args){
		InputStream in=null;
		OutputStream out=null;
		//给定一个URL地址
		try {
			URL url=new URL("");
			//建立通道
			URLConnection conn=url.openConnection();
			//通过URLConnection对象获取对象流
			 in=conn.getInputStream();
			File file =new File("D:URL");
			if(!file.exists()){
				file.mkdirs();//创建文件夹
			}
			out=new FileOutputStream(file.getPath()+"/"+"pag.png");
			byte[] buf=new byte[1024];
			int len =-1;
			System.out.println("下载开始........");
			while(-1!=(len=in.read(buf))){
				out.write(buf, 0, len);
			}
			System.out.println("下载成功........");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

1.2 UDP 服务端\客户端

//建立UDP的接收端
public class ReceiveDemo {
	public static void main(String[] args) throws IOException {
		
        //1.建立UDP Socket 接收端对象(DatagramSocket),因为要接收数据库,所以指明一个端口
		DatagramSocket ds =new  DatagramSocket(10003);
		System.out.println("接收端启动.........");
		
		//2.创建数据报包对象 ( DatagramPacket )
		byte[] buf=new byte[1024];
		DatagramPacket dp=new DatagramPacket(buf, buf.length);
		
		//3.使用  receive() 方法接受数据报包
		ds.receive(dp);//阻塞
		
		//4.通过数据报包对象的方法获取信息
		byte[] data=dp.getData();                  //获取发送过来的数据
		InetAddress ip=dp.getAddress();      //获取发送端的IP
		int port=dp.getPort();                       //获取发送端的端口号
		System.out.println(ip+"说了"+new String(data,0,dp.getLength()));
		ds.close();                                          //关闭流
	}
}

/**
 * 字节数组 +Data 输入流
 * @param data
 * @return
 * @throws IOException 
 */
public static double convert(byte[] data) throws IOException{
	DataInputStream dis =new DataInputStream(new ByteArrayInputStream(data));
	double num =dis.readDouble();  //此输入流的下八个字节,将它们解释为一个 double
	dis.close();
	return num;
}

//建立UDP的发送端
public class SendDemo {
	public static void main(String[] args) throws IOException {
		
		//1.建立UDP的DatagramSocket对象,指明对外的端口号
		DatagramSocket ds=new DatagramSocket(10002);
		System.out.println("发送端启动........");
		
		//2.通过DatagramPacket对象进行打包操作
		byte[] buf="测试,我爱你".getBytes();
		DatagramPacket dp=new DatagramPacket(buf, buf.length,
				InetAddress.getByName("127.0.0.1"),10003);
		
		//3.通过 DatagramSocket的 send() ,将数据报包发送到指定接收端
		ds.send(dp);
		
		ds.close();
	}
}

/**
 * 字节数组 数据源  +Data 输出流
 * @param num
 * @return
 * @throws IOException 
 */
public static byte[] convert(double num) throws IOException{
	byte[] data =null;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	DataOutputStream dos =new DataOutputStream(bos);
	dos.writeDouble(num);      // 将一个 double 值写入输出流
	
	  dos.flush();
	//获取数据
	data = bos.toByteArray();  
	// 创建一个新分配的 byte 数组其大小是此输出流的当前大小,并且缓冲区的有效内容已复制到该数组中。 
	
	dos.close();		
	return data;
	
  }
}

1.3 TCP 服务端/客户端

//TCP协议传输 : 服务器端的建立
/**步骤
 * 1.创建TCP服务器端的对象(ServerSocket)
 * 2.调用accept()方法获取连接带过来的客户端的Socket对象
 * 3.通过客户端的Scoket对象获取IO流来读取数据
 * 4.
 */
public class ServerDemo {
	public static void main(String[] args) throws IOException {
		ServerSocket server=new ServerSocket(10001);
		Socket client=null;
		InputStream in=null;
		System.out.println("服务器启动........");
		boolean b=true;
		while(b){
			client=server.accept( );          //侦听并接受到此套接字的连接
			in=client.getInputStream();    //返回此套接字的输入流。
			byte[] buf=new byte[1024];
			int len=in.read(buf);
			InetAddress ip=client.getInetAddress();
			System.out.println(ip+"说"+new String(buf,0,len));
		}
		server.close();
		client.close();
	}

}

//TCP协议传输 : 客户端的建立
/**步骤
 * 1.创建TCP客户端的对象(Socket)
 * 2.如果和服务器连接成功,通过Socket对象获取IO流
 * 3.使用IO流,对数据操作
 * 4.关闭资源
 */
public class ClientDemo {
	public static void main(String[] args) throws  IOException {
		Socket client=new Socket("127.0.0.1",10001);
		
		OutputStream out=client.getOutputStream();
		
		out.write("你好Server".getBytes());
		
		client.close();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值