• 网络编程-TCP程序实例(简单上传图片)


    package netTest;
    
    /*
     * 客户端: 
     *     1.服务端点
     *  2.读取客户端已有的图片数据
     *  3.通过socket输出流将数据发给服务端
     *  4.读取服务端的反馈信息
     *  5.关闭。
     * 
     */
    import java.io.*;
    import java.net.*;
    import java.util.concurrent.SynchronousQueue;
    public class Client {
        public static void main(String[] args) throws Exception {
            Socket s = new Socket(InetAddress.getLocalHost(),6333);
            FileInputStream fis = new FileInputStream("1.jpg");
            OutputStream out = s.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = fis.read(buf))!=-1){
                out.write(buf,0,len);
            }
            // 告诉服务端数据以写完
            s.shutdownOutput();
            InputStream in = s.getInputStream();
            byte[] bufIn =new byte[1024];
            int num = in.read(bufIn);
            System.out.println(new String(bufIn,0,num));
            fis.close();
            s.close();
        }
    }
    
    
    
    package netTest;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
    
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            ServerSocket ss = new ServerSocket(6333);
            // 得到客户端对象
            Socket s = ss.accept();
            InputStream in = s.getInputStream();
            FileOutputStream fos = new FileOutputStream("2.jpg");
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = in.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            OutputStream out = s.getOutputStream();
            out.write("上传成功".getBytes());
            out.close();
            s.close();
            ss.close();
        }
    
    }
  • 相关阅读:
    web测试知识点整理
    LINUX系统、磁盘与进程的相关命令
    压缩与解压
    LINUX基本操作命令
    linux命令管道工作原理与使用方法
    C#根据path文件地址进行下载
    C#向Word文档中的书签赋值
    网站发布
    乱码转换
    获取新增的数据ID
  • 原文地址:https://www.cnblogs.com/yangyongqian/p/5144030.html
Copyright © 2020-2023  润新知