简体   繁体   English

从客户端向服务器发送图像

[英]Sending image from client to server

Im new to JAVA so go easy on em please. 我是JAVA的新手,所以请放轻松。

I have a server and a client that can successfully connect to each other and other stuff but 1 function of the client is to send an image to the server.Can anybody provide the code for that(in java,not a web app). 我有一个服务器和一个客户端可以成功连接到彼此和其他东西,但客户端的一个功能是将图像发送到服务器。任何人都可以提供代码(在java中,而不是Web应用程序)。

Welcome to Java ! 欢迎来到Java!

To accomplish your task at hand, you can use Sockets. 要完成手头的任务,您可以使用套接字。

Client code : 客户代码:

function sendFile (String serverIp, int serverPort) {
    int i;
    FileInputStream fis = new FileInputStream ("/path/to/your/image.jpg");

    Socket sock = new Socket(serverIp, serverPort);
    DataOutputStream os = new DataOutputStream(sock.getOutputStream());
    while ((i = fis.read()) > -1)
        os.write(i);

    fis.close();
    os.close();
    sock.close();
}

Server code : 服务器代码:

function listenForFile(int port) {
    ServerSocket socket = new ServerSocket(serverPort);
        while (true) {

            Socket clientSocket = socket.accept();

            DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
            FileOutputStream fout = new FileOutputStream("/path/to/store/image.jpg");
            int i;
            while ( (i = dis.read()) > -1) {
                fout.write(i);
            }

            fout.flush();
            fout.close();
            dis.close();
            clientSocket.close();
        }
}

Note that server method listenForFile() must be called before you call sendFile() on client. 请注意,在客户端上调用sendFile()之前,必须先调用服务器方法listenForFile()。 And, serverPort must be same on both sides. 并且,serverPort必须在两侧都相同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM