简体   繁体   English

使用java套接字将文本文件从客户端发送到服务器

[英]Sending a text file from client to server using java sockets

This is an assignment. 这是一项任务。

Im looking for a bit of advice as to where i am going wrong here. 我正在寻找一些关于我在哪里出错的建议。 My aim is to read text from a file, send it to the server and write that text into a new file. 我的目标是从文件中读取文本,将其发送到服务器并将该文本写入新文件。

Problem being im not exactly sure how to do it, I have looked at many examples none of which being much help. 问题是我不确定如何做到这一点,我看了很多例子,但没有一点帮助。

To explain the program as is. 按原样解释该程序。 The user would be asked to input a code which relates to an if statemnt of that code. 将要求用户输入与该代码的if statemnt相关的代码。 The one i want to focus on is code 200 which is the upload file to server code. 我想关注的是代码200,它是服务器代码的上传文件。

When i run the code i have i get this error below. 当我运行代码时,我得到以下错误。 Could someone explain to me where i am going wrong, I'd appreciate it. 有人可以向我解释我哪里出错了,我会很感激。

    Connection request made
Enter Code: 100 = Login, 200 = Upload, 400 = Logout:
200
java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
        at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
        at sun.nio.cs.StreamDecoder.read(Unknown Source)
        at java.io.InputStreamReader.read(Unknown Source)
        at java.io.BufferedReader.fill(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at MyStreamSocket.receiveMessage(MyStreamSocket.java:50)
        at EchoClientHelper2.getEcho(EchoClientHelper2.java:34)
        at EchoClient2.main(EchoClient2.java:99)

And this error on the server: 而且这个错误在服务器上:

    Waiting for a connection.
connection accepted
message received: 200
java.net.SocketException: Socket is not connected
        at java.net.Socket.getInputStream(Unknown Source)
        at EchoServer2.main(EchoServer2.java:71)

Your MyStreamSocket class does not need to extend Socket. 您的MyStreamSocket类不需要扩展Socket。 The mysterious error message is because the Socket represented by MyStreamSocket is never connected to anything. 神秘的错误消息是因为MyStreamSocket表示的Socket永远不会连接到任何东西。 The Socket referenced by its socket member is the one that is connected. socket成员引用的Socket是连接的Socket。 Hence when you get the input stream from MyStreamSocket it genuinely is not connected. 因此,当您从MyStreamSocket获取输入流时,它真的没有连接。 That causes an error, which means the client shuts down. 这会导致错误,这意味着客户端会关闭。 That causes the socket to close, which the server duly reports 这导致套接字关闭,服务器正式报告

The use of BufferedReader is going to cause you problems. BufferedReader的使用会给你带来麻烦。 It always reads as much as it can into its buffer, so at the start of a file transfer it will read the "200" message and then the first few Kb of the file being sent which will get parsed as character data. 它总是尽可能多地读入缓冲区,因此在文件传输开始时它会读取“200”消息,然后是正在发送的文件的前几个Kb,它将被解析为字符数据。 The result will be a whole heap of bugs. 结果将是一堆错误。

I suggest you get rid of BufferedReader right now and use DataInputStream and DataOutputStream instead. 我建议你现在摆脱BufferedReader并改用DataInputStream和DataOutputStream。 You can use the writeUTF and readUTF methods to send your textual commands. 您可以使用writeUTF和readUTF方法发送文本命令。 To send the file I would suggest a simple chunk encoding. 要发送文件,我建议一个简单的块编码。

It's probably easiest if I give you code. 如果我给你代码,这可能是最简单的。

First your client class. 首先是您的客户端类。

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

public class EchoClient2 {

    public static void main(String[] args) {
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(is);

        File file = new File("C:\\MyFile.txt");

        try {
            System.out.println("Welcome to the Echo client.\n"
                    + "What is the name of the server host?");
            String hostName = br.readLine();
            if( hostName.length() == 0 ) // if user did not enter a name
                hostName = "localhost"; // use the default host name
            System.out.println("What is the port number of the server host?");
            String portNum = br.readLine();
            if( portNum.length() == 0 ) portNum = "7"; // default port number
            MyStreamSocket socket = new MyStreamSocket(
                    InetAddress.getByName(hostName), Integer.parseInt(portNum));
            boolean done = false;
            String echo;
            while( !done ) {

                System.out.println("Enter Code: 100 = Login, 200 = Upload, 400 = Logout: ");
                String message = br.readLine();
                boolean messageOK = false;

                if( message.equals("100") ) {
                    messageOK = true;
                    System.out.println("Enter T-Number: (Use Uppercase 'T')");
                    String login = br.readLine();
                    if( login.charAt(0) == 'T' ) {
                        System.out.println("Login Worked fantastically");
                    } else {
                        System.out.println("Login Failed");
                    }
                    socket.sendMessage("100");
                }

                if( message.equals("200") ) {
                    messageOK = true;
                    socket.sendMessage("200");
                    socket.sendFile(file);
                }
                if( (message.trim()).equals("400") ) {
                    messageOK = true;
                    System.out.println("Logged Out");
                    done = true;
                    socket.sendMessage("400");
                    socket.close();
                    break;
                }

                if( ! messageOK ) {
                    System.out.println("Invalid input");
                    continue;
                }

                // get reply from server
                echo = socket.receiveMessage();
                System.out.println(echo);
            } // end while
        } // end try
        catch (Exception ex) {
            ex.printStackTrace();
        } // end catch
    } // end main
} // end class

Then your server class: 那你的服务器类:

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

public class EchoServer2 {
    static final String loginMessage = "Logged In";

    static final String logoutMessage = "Logged Out";


    public static void main(String[] args) {
        int serverPort = 7; // default port
        String message;

        if( args.length == 1 ) serverPort = Integer.parseInt(args[0]);
        try {
            // instantiates a stream socket for accepting
            // connections
            ServerSocket myConnectionSocket = new ServerSocket(serverPort);
            /**/System.out.println("Daytime server ready.");
            while( true ) { // forever loop
                // wait to accept a connection
                /**/System.out.println("Waiting for a connection.");
                MyStreamSocket myDataSocket = new MyStreamSocket(
                        myConnectionSocket.accept());
                /**/System.out.println("connection accepted");
                boolean done = false;
                while( !done ) {
                    message = myDataSocket.receiveMessage();

                    /**/System.out.println("message received: " + message);

                    if( (message.trim()).equals("400") ) {
                        // Session over; close the data socket.
                        myDataSocket.sendMessage(logoutMessage);
                        myDataSocket.close();
                        done = true;
                    } // end if

                    if( (message.trim()).equals("100") ) {
                        // Login
                        /**/myDataSocket.sendMessage(loginMessage);
                    } // end if

                    if( (message.trim()).equals("200") ) {

                        File outFile = new File("C:\\OutFileServer.txt");
                        myDataSocket.receiveFile(outFile);
                        myDataSocket.sendMessage("File received "+outFile.length()+" bytes");
                    }

                } // end while !done
            } // end while forever
        } // end try
        catch (Exception ex) {
            ex.printStackTrace();
        }
    } // end main
} // end class

Then the StreamSocket class: 然后是StreamSocket类:

public class MyStreamSocket {
    private Socket socket;

    private DataInputStream input;

    private DataOutputStream output;


    MyStreamSocket(InetAddress acceptorHost, int acceptorPort)
            throws SocketException, IOException {
        socket = new Socket(acceptorHost, acceptorPort);
        setStreams();
    }


    MyStreamSocket(Socket socket) throws IOException {
        this.socket = socket;
        setStreams();
    }


    private void setStreams() throws IOException {
        // get an input stream for reading from the data socket
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }


    public void sendMessage(String message) throws IOException {
        output.writeUTF(message);
        output.flush();
    } // end sendMessage


    public String receiveMessage() throws IOException {
        String message = input.readUTF();
        return message;
    } // end receiveMessage


    public void close() throws IOException {
        socket.close();
    }


    public void sendFile(File file) throws IOException {
        FileInputStream fileIn = new FileInputStream(file);
        byte[] buf = new byte[Short.MAX_VALUE];
        int bytesRead;        
        while( (bytesRead = fileIn.read(buf)) != -1 ) {
            output.writeShort(bytesRead);
            output.write(buf,0,bytesRead);
        }
        output.writeShort(-1);
        fileIn.close();
    }



    public void receiveFile(File file) throws IOException {
        FileOutputStream fileOut = new FileOutputStream(file);
        byte[] buf = new byte[Short.MAX_VALUE];
        int bytesSent;        
        while( (bytesSent = input.readShort()) != -1 ) {
            input.readFully(buf,0,bytesSent);
            fileOut.write(buf,0,bytesSent);
        }
        fileOut.close();
    }    
} // end class

Ditch the "helper" class. 抛弃“助手”类。 It is not helping you. 它没有帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用套接字(java)从客户端向服务器发送文件成功,但是客户端冻结并且未退出循环 - Sending a file using sockets (java) from a client to the server succeeds but the client freezes and does not exit the loop Java套接字-从客户端向服务器发送数据 - Java Sockets - Sending data from client to server Java套接字 - 将文件从客户端发送到服务器 - Java Sockets - Send a file from the Client to the Server 使用Java套接字将文件从服务器传输到客户端。 服务器端错误,文件传输到客户端为空 - File Transfer from Server to Client using java sockets. Error on Server side and File transferred to client is empty 从Java服务器向C客户端发送文本文件 - Sending a text file from Java server to C client 使用套接字立即将数据从服务器发送到客户端时出现问题? - Problem in sending data from server to Client immidiately using sockets? 使用 sockets 从客户端向服务器发送 JFrame 绘图 - Sending a JFrame drawing from Client to Server using sockets 套接字,java发送文件服务器客户端 - sockets, java sending files server client 使用套接字将图像从客户端发送到服务器 - Sending images from client to server with sockets 如何使用 Java 中的套接字访问客户端 - 服务器架构中的文件? - How to access a file in Client-Server architecture using Sockets in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM