Socket协议

5.Socket
5.1获取主机地址对象

  InetAddress inetAddress= InetAddress.getByName("DESKTOP-JSV4VJA");//主机名/ip地址

5.2协议介绍
udp:面向无连接,数据不完整,不安全/效率高(发短信,QQ视频)
tcp:传输控制协议,面向有连接,数据是安全的,完整性(打电话,发短信)
建立三个步骤:三次握手
5.3 upd发送端 DatagramSocket DatagramPacket

    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket();
        byte[] bs="我爱你".getBytes();
        DatagramPacket dp=new DatagramPacket(bs,bs.length,InetAddress.getByName("DESKTOP-JSV4VJA"),12345);
        ds.send(dp);
        System.out.println("发送成功");
    }

5.4发送端接收端小案例 (先启用接受端)
客户端

  public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true){
            String text= scanner.nextLine();
            DatagramSocket ds=new DatagramSocket();
            byte[] bs=text.getBytes();
            DatagramPacket dp=new DatagramPacket(bs,bs.length,InetAddress.getByName("DESKTOP-JSV4VJA"),12345);
            ds.send(dp);
            System.out.println("发送成功");
        }

服务端

  public static void main(String[] args) throws Exception {
        DatagramSocket ds=new DatagramSocket(12345);
        while (true) {
            byte[] bs = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bs, bs.length);
            ds.receive(dp);
            System.out.println("接收数据成功");
            InetAddress sendAddress = dp.getAddress();//获取发送端地址
            System.out.println("发送端地址:" + sendAddress.getHostAddress() + "sendAddress" + sendAddress);
            byte[] data = dp.getData();
            int len = dp.getLength();
            String receiveMsg = new String(data, 0, len);
            System.out.println("发送端说" + receiveMsg);
        }
        //ds.close();
    }

5.3 Client与Socket的使用
客户端

public static void main(String[] args) throws IOException {
        Socket client=new Socket("localhost",12345);
        OutputStream out = client.getOutputStream();
        out.write("How are you".getBytes());
        System.out.println("给服务器发送数据成功!");
        InputStream inputStream = client.getInputStream();
        byte[] bytes = new byte[1024];
        int len=inputStream.read(bytes);
        System.out.println("客户端:"+new String(bytes,0,len));
        client.close();
        out.close();
    }

服务端

 public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(12345);
        System.out.println("等待客户端的连接");
        Socket client=  server.accept();//此方法等待客户端连接,一直等
        String address = client.getInetAddress().getHostAddress();
        System.out.println("服务器已经与客户端成功连接!当前服务器的ip:"+address);
        InputStream stream = client.getInputStream();//输入流:客户端写数据的输出流
        byte[] bs=new byte[1024];
        int len=stream.read(bs);
        System.out.println("客户端:"+new String(bs,0,len));

        OutputStream outputStream = client.getOutputStream();
        outputStream.write("已经收到您的消息!".getBytes());
        server.close();
        stream.close();
        client.close();
    }

5.3 Client与Socket的使用 增强版

	 /**
	 * 客户端
	 */
	public static void main(String[] args)throws IOException {
		Socket client = new Socket("127.0.0.1", 12345);
		System.out.println("正在建立连接..");
		OutputStream out = client.getOutputStream();
		FileInputStream fis = new FileInputStream("D:\\timg.jpg");
		byte[] bs = new byte[1024];
		int len = 0;
		while((len=fis.read(bs))!=-1){
			out.write(bs, 0, len);
		}
		client.shutdownOutput();
		InputStream in = client.getInputStream();
		byte[] bs1 = new byte[1024];
		int len1 = in.read(bs1);
		System.out.println("服务端说:"+new String(bs1,0,len1));
		//6�ر�
		client.close();
		out.close();
		fis.close();
	}
	 /**
	 * 服务端
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ServerSocket server = new ServerSocket(12345);
		System.out.println("等待客户端连接...");
		Socket client = server.accept();
		InputStream in = client.getInputStream();
		String picName = "D:\\upload\\"+System.currentTimeMillis()+".jpg";
		FileOutputStream fos = new FileOutputStream(picName);
		byte[] bs = new byte[1024];
		int len = 0;
		while((len=in.read(bs))!=-1){
			fos.write(bs, 0, len);
		} 
		System.out.println("您要存储的路径为:"+picName);
		OutputStream out = client.getOutputStream();
		out.write("您的文件上传成功!".getBytes());
		server.close();
		client.close();
		in.close();
		out.close();
		fos.close();
		
	}
 	/**
	 * 服务端 多线程版本
	 */
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(12345);
		while(true){
			System.out.println("等待客户端连接...");
			final Socket client = server.accept();
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("小样:"+client.getInetAddress().getHostAddress());
						InputStream in = client.getInputStream();
						String picName = "H:\\upload\\"+System.currentTimeMillis()+".jpg";
						FileOutputStream fos = new FileOutputStream(picName);
						byte[] bs = new byte[1024];
						int len = 0;
						while((len=in.read(bs))!=-1){
							fos.write(bs, 0, len);
						}
						System.out.println("您要保存的文件为:"+picName);
						OutputStream out = client.getOutputStream();
						out.write("您的文件已经保存成功!".getBytes());
						client.close();
						in.close();
						out.close();
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
			
		}
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值