[英]Sending image from client to server
我是JAVA的新手,所以請放輕松。
我有一個服務器和一個客戶端可以成功連接到彼此和其他東西,但客戶端的一個功能是將圖像發送到服務器。任何人都可以提供代碼(在java中,而不是Web應用程序)。
歡迎來到Java!
要完成手頭的任務,您可以使用套接字。
客戶代碼:
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();
}
服務器代碼:
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();
}
}
請注意,在客戶端上調用sendFile()之前,必須先調用服務器方法listenForFile()。 並且,serverPort必須在兩側都相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.