集册 Java实例教程 简单文件套接字客户端

简单文件套接字客户端

欢马劈雪     最近更新时间:2020-01-02 10:19:05

557
简单文件套接字客户端

import java.net.Socket;

import java.io.IOException;//n o w j a v a . c o m - 时代Java 提供

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.BufferedOutputStream;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.FileOutputStream;

import java.net.InetAddress;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Scanner;// 来 自 N o  w  J a v a . c o m - 时  代  Java

import java.io.File;



public class SimpleFileClient {


  public final static int SOCKET_PORT = 1234;      

  public final static String SERVER = "localhost"; 

  public static String FILE_TO_RECEIVED = "D:/DownlaodedText.txt";  


  public static int FILE_SIZE = 2048;


  public static void main (String [] args ) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {

      int bytesRead;

      int current = 0;

      FileOutputStream fos = null;

      BufferedOutputStream bos = null;

      Socket sock = null;

      ObjectOutputStream oos = null;

      ObjectInputStream ois = null;

      String option;

      Scanner sc = new Scanner(System.in);

      sock = new Socket("localhost", 1234);

      oos = new ObjectOutputStream(sock.getOutputStream());

      System.out.println("Sending request to Socket Server");

      ois = new ObjectInputStream(sock.getInputStream());

      String message = (String) ois.readObject();

      System.out.println("Message: " + message);

      option = sc.nextLine();

      System.out.println("Sending to Message : " + option);

      oos.writeObject(option);

      System.out.println("mark");

    try {

      byte [] mybytearray  = new byte [FILE_SIZE];

      InputStream is = sock.getInputStream();

      fos = new FileOutputStream(FILE_TO_RECEIVED);

      bos = new BufferedOutputStream(fos);

      bytesRead = is.read(mybytearray,0,mybytearray.length);

      current = bytesRead;


      do {

         bytesRead =

            is.read(mybytearray, current, (mybytearray.length-current));

         
展开阅读全文