黑马程序员-java网络编程

UDP

将数据及源和目的封装成数据包,不需要建立连接

每个数据包的大小限制在64K内

因无连接,是不可靠协议

不需要建立连接,速度快

TCP

建立连接,形成传输数据的通道

在连接中可以进行大数据量的传输

通过三次握手完成连接,是可靠协议

必须建立连接,效率会比udp稍低


UDP网络聊天示例

import java.io.*;
import java.net.*;
class Send implements Runnable{
	private DatagramSocket ds;
	public Send(DatagramSocket ds){
		this.ds = ds;
	}
	
	public void run(){
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			
			while((line=br.readLine())!=null){
				if("886".equals(line)){
					break;
				}
				byte[] buf = line.getBytes();
				
				DatagramPacket dp = 
						new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.1"),10000);
				ds.send(dp);
			}
		}catch(Exception e){
			throw new RuntimeException("出现错误");
		}
	}
}


class Rece implements Runnable{
	private DatagramSocket ds;
	public Rece(DatagramSocket ds){
		this.ds = ds;
	}
	
	public void run(){
		try{
			while(true){
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf,buf.length);
				ds.receive(dp);
				
				String ip = dp.getAddress().getHostAddress();
				
				String data = new String(dp.getData(),0,dp.getLength());
				
				System.out.println(ip+"::"+ip+"::"+data);
			}
		}catch (Exception e){
			throw new RuntimeException("接收出现错误");
		}
	}
}
//启动程序
class ChatDemo {
	public static void main(String[] args) throws Exception{
		DatagramSocket sendSocket = new DatagramSocket();//发送端可以不指定端口
		DatagramSocket receSocket = new DatagramSocket(10000);//接收端必须指定接收端口
		
		new Thread(new Send(sendSocket)).start();
		new Thread(new Rece(receSocket)).start();
	}
}


TCP连接示例

class TcpClient{
	public static void main(String[] args){
		//创建客户端的socket服务。指定目的主机和端口
		Socket s = new Socket("192.168.1.1",10000);
		
		//为了发送数据,应该获取socket流中的输出流。
		OutputStream out = s.getOutputStream();
		//s.getInputStream();
		out.write("sdfsdfsd".getBytes());
		s.close();
	}
}

class TcpServer{
	public static void main(String[] args){
		//建立服务端socket服务。监听一个端口
		ServerSocket ss = new ServerSocket(10000);
		//通过accept方法获得连接过来的客户端对象。
		Socket s = ss.accept();
		
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+".....connected");
		//获取客户端发送过来的数据,那么要使用客户对象的读取流来读取数据。
		InputStream in = s.getInputStream();
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		
		System.out.println(new String(buf,0,len));
		
		s.close();//关闭客户端
		ss.close();//关闭服务端
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值