发送zip文件java c#application socket

时间:2017-05-04 11:03:43

标签: java c# sockets

大家好我试图通过套接字发送txt使用以下源代码工作,但当我想发送zip文件时我得到了一个例外。任何帮助将不胜感激谢谢  Java服务器

import java.net.*;
import java.io.*;

public class Server {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub}
        sendFile("FileTest.rar");
    }
    public static Boolean sendFile(String strFileToSend) {
        try {
            ServerSocket serverSocket = new ServerSocket(1592);
            Socket socket = serverSocket.accept();
            System.out.println("Connection accepted from " + socket);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            File file = new File(strFileToSend);
            // send file length
            out.println(file.length());
            // read file to buffer
            byte[] buffer = new byte[(int) file.length()];
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            dis.read(buffer, 0, buffer.length);
            // send file
            BufferedOutputStream bos = new BufferedOutputStream(
                    socket.getOutputStream());
            bos.write(buffer);
            bos.flush();
            // added
            dis.close();
            serverSocket.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

C#客户端

public static bool receiveFile(string ip,string strFilePath)
        {   

            try
            {
                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(ip, 1592);
                NetworkStream networkStream = tcpClient.GetStream();
                StreamReader sr = new StreamReader(networkStream);
                //read file length
                int length = int.Parse(sr.ReadLine());

                //read bytes to buffer
                byte[] buffer = new byte[length];
                networkStream.Read(buffer, 0, (int)length);
                //write to file
                BinaryWriter bWrite = new BinaryWriter(File.Open(strFilePath, FileMode.Create));
                bWrite.Write(buffer);
                bWrite.Flush();
                bWrite.Close();
                return true;
            }
            catch(Exception exException)
            {
                MessageBox.Show(exException.Message);
                return false;
            }
            }

问题是当我想处理rar或zip文件时。 提前致谢

我得到了下面的例子。它发生在客户端应用中的这一行 int length = int.Parse(sr.ReadLine());

enter image description here

0 个答案:

没有答案