问题:
利用Socket编程技术实现客户端向服务端上传一个图片的程序。
客户端:
import java.io.*;import .Socket;public class client{public static byte[] getimg(String imgpath) throws IOException{FileInputStream img = new FileInputStream(imgpath); //读取图片的字节流ByteArrayOutputStream out = new ByteArrayOutputStream();byte[] res = new byte[1024];int num = 0;while ((num = img.read(res)) != -1){out.write(res, 0, num); //写入}return out.toByteArray();}public static void main(String[] args) throws IOException{Socket s = new Socket("127.0.0.1", 10000);OutputStream out = s.getOutputStream();byte[] a = getimg("E:\\1.jpg"); //得到图片的字节数组out.write(a); //写入s.close();out.close();}}
服务端:
import java.io.*;import .ServerSocket;import .Socket;public class server{public static void main(String[] args) throws IOException{ServerSocket now = new ServerSocket(10000);Socket s = now.accept();InputStream in = s.getInputStream();ByteArrayOutputStream out = new ByteArrayOutputStream();int tr;byte[] u = new byte[1024];while ((tr = in.read(u)) != -1){out.write(u, 0, tr); //写入out}FileOutputStream fileout = new FileOutputStream("E:\\2.jpg");fileout.write(out.toByteArray()); //写入图片文件out.close();}}