分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

Socket编程模仿上传本地图片,并且响应客户端

发布时间:2023-09-06 01:46责任编辑:苏小强关键词:暂无标签

服务端:

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved