面向常考---客户端or服务端

(1)客户端

   public class MyClient {
    public static void main(String[] args) {
        MyClient client = new MyClient();
        try {
            client.sendFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void sendFile() throws IOException {
        Socket socket = new Socket();
        //设定连接的IP地址和端口
        SocketAddress socketAddress = new InetSocketAddress("localhost",9080);
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        byte[] buffer = new byte[1024];
        try {
            //连接到IP地址
            socket.connect(socketAddress);
            //FileInputStream用于在读取从本地文件读取输入
            fileInputStream = new FileInputStream("/tmp/src.data");
            //从socket中获得输出,从本地的输入中读取并写入它
            fileOutputStream= (FileOutputStream) socket.getOutputStream();
            int length=0;
            //从本地的socket中读取
            while((length=fileInputStream.read(buffer,0,buffer.length-1))!=-1){
                //写入
                fileOutputStream.write(buffer,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fileInputStream.close();
            fileOutputStream.close();
            if(socket!=null && socket.isConnected()){
                socket.close();
            }
        }
    }
}

(2)服务端

 public class MyServer {
    public static void main(String[] args) {
        MyServer server = new MyServer();
        try {
            server.receiveFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void receiveFile() throws IOException {
        Socket clientSocket = null;
        InputStream inputStream=null;
        FileOutputStream fileOutputStream=null;
        byte[] buffer = new byte[1024];

        try {
            //服务端指监听端口
            ServerSocket serverSocket = new ServerSocket(10000);
            //服务端接受
            clientSocket = serverSocket.accept();
            //获得客户端输入流
            inputStream = clientSocket.getInputStream();
            //创建自己的本地输出流
            fileOutputStream = new FileOutputStream("/tmp/data");
            int length = 0;
            //从socket的输入流中读入数量写到自己的本地输出流中
            while((length=inputStream.read(buffer,0,buffer.length-1))!=-1){
                fileOutputStream.write(buffer,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
            fileOutputStream.close();
            if(clientSocket!=null && clientSocket.isConnected()){
                clientSocket.close();
            }
        }
    }
}


你可能感兴趣的:(面向常考---客户端or服务端)