服务端:
package com.huan.yu1;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class ServerSokcetDemo1 implements Runnable {private Socket s;public ServerSokcetDemo1(Socket s) {super();this.s = s;}/** * 定义一个线程 */@Overridepublic void run() {// 读取客户端的数据进行上传int count = 1;String ip = s.getInetAddress().getHostAddress();System.err.println(ip + "---connect");// 读取客户端发过来得数据try {InputStream is = s.getInputStream();// 定义目的地byte[] b = new byte[1024 * 4];File file = new File("F://ppp");if (!file.exists()) {file.mkdir();}// 重新定义上传文件的路径和名称File child = new File(file, ip + "00" + count + ".jpg");// 如果存在就重新创建while (child.exists()) {child = new File(file, ip + "00" + count + ".jpg");}FileOutputStream fos = new FileOutputStream(child);int len = 0;while ((len = is.read(b)) != -1) {fos.write(b);}OutputStream out = s.getOutputStream();out.write("上传成功".getBytes());fos.close();s.close();} catch (IOException e) {e.printStackTrace();}}/** * 客户端上传数据 * ?* @throws IOException */@SuppressWarnings("resource")public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(10666);while (true) {Socket s = ss.accept();new Thread(new ServerSokcetDemo1(s)).start();;}}}
客户端:
package com.huan.yu1;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class ClientSocket {/** * 客户端 * ?* @throws IOException * @throws UnknownHostException */@SuppressWarnings("resource")public static void main(String[] args) throws UnknownHostException, IOException {// 请求服务,并且要将数据上传上去//本地ipSocket s = new Socket("192.168.86.1", 10666);FileInputStream fis = new FileInputStream("F://picture//1920.png");OutputStream os = s.getOutputStream();byte[] b = new byte[1024 * 4];int len = 0;while ((len = fis.read(b)) != -1) {os.write(b);}// 告诉服务器读取完毕s.shutdownOutput();// 读取服务器的数据InputStream is = s.getInputStream();byte[] b1 = new byte[1024 ];int len1=is.read(b1);String str=new String(b1,0,len1);System.err.println(str);fis.close();s.close();is.close();}}
Socket编程模仿上传本地图片,并且响应客户端
原文地址:https://www.cnblogs.com/liushisaonian/p/8595285.html