006socket基本使用

    技术2022-07-10  104

    package sock; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class MySock6 { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("只能搞一个啊,别乱来"); return; } // String name = "d:/美女.jpg"; File file = new File(args[0]); if (!(file.exists() && file.isFile())) { System.out.println("不存在或者不是文件!"); return; } if(!file.getName().endsWith(".jpg")){ System.out.println("只能是.jgp格式,知道不?"); return; } //k m if (file.length() > 5 * 1024 * 1024) { System.out.println("设备太先进的不行哈,怀旧"); return; } FileInputStream inputStream = new FileInputStream(file); byte[] arr = new byte[1234]; int res = 0; Socket socket = new Socket("127.0.0.1", 12331); OutputStream out = socket.getOutputStream(); while ((res = inputStream.read(arr)) != -1) { out.write(arr); } socket.shutdownOutput(); InputStream in2 = socket.getInputStream(); byte[] bytes = new byte[1234]; int read = in2.read(bytes); System.out.println(new String(bytes,0,read,"utf-8")); inputStream.close(); socket.close(); } } class MySer6{ public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(12331); byte[] bytes1 = "我是中文,你翻译看看".getBytes("utf-8"); System.out.println(new String(bytes1)); while (true) { Socket accept = serverSocket.accept(); new Thread(new MyThead(accept)).start();//如果是main执行会怎样? } } } class MyThead implements Runnable{ Socket accept; public MyThead(Socket accept) { this.accept = accept; } @Override public void run() { int count = 1; String ip = accept.getInetAddress().getHostAddress(); try { System.out.println( ip+"...............来了"); File file = new File("d:/cop有美女"+ip+".jpg"); while (file.exists()) { file = new File("d:/"+"("+(count++)+")"+"cop有美女"+ip+".jpg"); } InputStream inputStream = accept.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] bytes = new byte[1234]; int res = 0; while ((res = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes); } OutputStream outputStream = accept.getOutputStream(); outputStream.write("我也得到美女了".getBytes()); fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(ip + ":没有得到美女啊,可惜了"); } finally { } } }
    Processed: 0.013, SQL: 9