[英]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.