Android TCP协议与UDP协议的实现

本文介绍了TCP和UDP两种网络通信协议的基本原理及应用实例。通过具体的Java代码演示了如何使用这两种协议进行客户端与服务器之间的数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TCP协议:

安卓真机与PC之间可以通过ServerSocket 与 Socket进行通信,使用的是TCP/IP协议。(TCP对网络要求很高,具有可靠的安全性)

服务器:

public class Server {
  public static void main(String[] args) {
	new Server().Server(9090);
}
  public void Server(int port){
	  
	 try{
		 ServerSocket server=new ServerSocket(port);
		 System.out.println("服务器已经启动。。。。等待客户端连接");
		 Socket connect=server.accept();
		 System.out.println("客户端连上,IP:"+connect.getInetAddress());
		 


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

客户端:
                        final EditText ed2=(EditText)rootView.findViewById(R.id.login_user);
			final EditText ed1=(EditText)rootView.findViewById(R.id.login_pwd);
			Button login_button=(Button)rootView.findViewById(R.id.login_button);
			
			//文件流 -------TCP-----//
			File file=new File("/storage/sdcard/first.txt");
			try{//读文件
				FileInputStream fls=new FileInputStream(file);
				BufferedInputStream bis=new BufferedInputStream(fls);
				byte[] bytes=new byte[bis.available()];
				bis.read(bytes);
				String st=new String(bytes);
				int i=st.indexOf("a");	
				String user=st.substring(0,i);
				String pwd=st.substring(i+1);
				
				ed2.setText(user);
				ed1.setText(pwd);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			
			
			login_button.setOnClickListener(new OnClickListener() 
			{
				public void onClick(View v) {
					String user=ed2.getText().toString();
					String pwd=ed1.getText().toString();
					
					
					if("1".equals(user)&&"1".equals(pwd)){
						File file=new File("/storage/sdcard/first.txt");
						   if(!file.exists())try{
							   file.createNewFile();
						   }catch (Exception e) {
							   e.printStackTrace();
						}
						 try{
							 FileOutputStream fos=new FileOutputStream(file);
							 String st1=ed2.getText().toString()+"a"+ed1.getText().toString();
							 byte[] byte1=st1.getBytes();
							 fos.write(byte1);
						 } catch(Exception e){
							 e.printStackTrace();
						 } 
服务器连接成功,真机就可以和服务器交互,发送信息。
<img src="https://img-blog.youkuaiyun.com/20160708004000066?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

UDP协议:是一种不安全的协议,在电脑QQ上可以找到,在网络良好的情况下,会使用TCP,网络差的情况会自动切换成UDP,但容易丢失信息。   



 客户端:

   public void testClient(){  
        try{  
            DatagramSocket ds = new DatagramSocket();  
            System.out.println("客户端socket已经创建完成...");  
            byte[] buf = "a a a a   a a a a".getBytes();  
            String host = "192.168.215.1";  
            InetAddress ia = InetAddress.getByName(host);  
            DatagramPacket dp = new DatagramPacket(buf,buf.length,ia,9090);  
            System.out.println("客户端数据包创建完成...");  
            ds.send(dp);  
            System.out.println("客户端数据包已经发送给服务器");  
            ds.close();  
            System.out.println("客户端socket已经关闭...");  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }  
服务器:
    public void CreateServer(){  
        try{  
            DatagramSocket ds = new DatagramSocket(9090);  
            System.out.println("服务端连接已经建立...");  
            byte[] buf = new byte[16];  
            DatagramPacket dp = new DatagramPacket(buf,buf.length);  
            System.out.println("创建数据包完成...");  
            ds.receive(dp);  
            System.out.println("已经接收数据包...");  
            String data = new String(dp.getData());  
            String host = dp.getAddress().getHostAddress();  
            int port = dp.getPort();  
            System.out.println("data:\t"+data+"  host:\t"+host+"  port:\t"+port);  
            ds.close();  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }

UDP实现的效果图:
 


总结:

   自己对TCP和UDP的了解还不是太深刻,什么情况,具体怎么去用还是不太清晰,以后还需要进行深刻的认知与了解。

  希望此博客能帮助到遇到问题的朋友!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值