客户端 java.net.Socket
服务端 java.net.ServerSocket
客户端和服务端直接是逻辑连接,其中包含一个IO对象(字节流对象), 服务端用客户端的流跟客户端交互。
serversocket.accept()获取客户端的Socket请求对象
Server端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package file.upload;
import java.io.*; import java.net.ServerSocket; import java.net.Socket;
public class FileUploadServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8000); while(true){ Socket accept = server.accept(); new Thread(new Runnable() { @Override public void run() { try{ InputStream inputStream = accept.getInputStream(); File file = new File("D:\\upload"); if(!file.exists()){ file.mkdirs(); } FileOutputStream fileOutputStream = new FileOutputStream(file +"\\"+System.currentTimeMillis()+".gif");
int len = 0; byte[] bytes = new byte[1024 * 10]; while ((len = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); }
accept.getOutputStream().write("接收完毕".getBytes()); fileOutputStream.close();
}catch (IOException e){ e.printStackTrace(); }finally { try { accept.close(); }catch (IOException e){ e.printStackTrace(); } }
} });
}
} }
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package file.upload;
import java.io.*; import java.net.Socket;
public class FileUploadClient { public static void main(String[] args) throws IOException { FileInputStream file = new FileInputStream("D:\\vim.gif"); byte[] bytes = new byte[1024 * 10]; int readLen = 0;
Socket socket = new Socket("127.0.0.1", 8000);
OutputStream outputStream = socket.getOutputStream(); while ((readLen = file.read(bytes)) != -1) { outputStream.write(bytes,0,readLen); } socket.shutdownOutput();
InputStream inputStream = socket.getInputStream(); while ((readLen = inputStream.read(bytes)) != -1) { System.out.println(new String(bytes, 0, readLen)); }
file.close(); socket.close(); } }
|
最后更新时间:
各位大爷们,评论在下最方,打赏点下面。转载请注明GitHub项目地址:https://github.com/wordfeng/wordfeng.github.io