TCP
方便起见,所有代码都直接throws异常,没有处理
以“Client把文件上传至Server为例”
Client端
- Socket s = new Socket(“Sever的IP地址” , 端口号);
- OutputStream os = s.getOutputStream();
-
先建立Socket连接
-
“上传文件”,所以getOutputStream
-
普通IO(FileInputStream)先读取文件,然后赋值给网络IO流
public class Client9548 { public static void main(String[] args) throws IOException { //Client IP:192.168.3.82 Socket clientsocket = new Socket("192.168.3.47",9548);//Server的IP,共用的端口 File file = new File("D:\\FFOutput\\201983250028张家豪.docx"); OutputStream outputStream = clientsocket.getOutputStream();//从Client输出 FileInputStream fis = new FileInputStream(file); byte[] bbuf = new byte[1024]; int len; while((len=fis.read(bbuf))!=-1){ outputStream.write(bbuf,0,len); } outputStream.close(); fis.close(); }
}
Server端
- ServerSocket ss = new ServerSocket(端口号);
- Socket s = ss.accept();
- InputStream is = s.getInputStream();
- Server端会多一个ServerSocket端口,并且也需要额外关闭
- “接受文件”,所以s.getInputStream();
- 其他的本地读写操作都是普通IO
public class Server9548 {
public static void main(String[] args) throws IOException {
//Server IP:192.168.3.47
ServerSocket serverSocket = new ServerSocket(9548);//new ServerSocket,端口和Client端口保持一致
Socket sa = serverSocket.accept();//SeverScoket——>socket
InputStream is = sa.getInputStream();//输入流,接受来自Client的文件数据
//这下面创建输出流,保存在硬盘
File file = new File("D:\\fromClient\\file4.docx");
FileOutputStream fos = new FileOutputStream(file);
byte[] bbuf = new byte[1024];
int len;
while((len=is.read(bbuf))!=-1){
fos.write(bbuf);
}
fos.close();
sa.close();
serverSocket.close();//注意接口关闭
}
}
URL
常用方法
URL url = new URL("http://localhost:8080/examples/myTest.txt");
System.out.println("getProtocol() :"+url.getProtocol());
System.out.println("getHost() :"+url.getHost());
System.out.println("getPort() :"+url.getPort());
System.out.println("getPath() :"+url.getPath());
System.out.println("getFile() :"+url.getFile());
System.out.println("getQuery() :"+url.getQuery());
从指定网址下载指定文件
public class URLTest1 {
public static void main(String[] args) throws IOException {
URL url1 = new URL("https://img-blog.csdnimg.cn/img_convert/5cef01f2bb72055365b892b39b01cdfb.png");//URL地址
HttpURLConnection hURLc = (HttpURLConnection) url1.openConnection();//建立URL连接+强转
hURLc.connect();//连接
//从该URL地址下载,input流
InputStream URLis = hURLc.getInputStream();
//导入本地,普通IO
File file = new File("temp1.jpg");
FileOutputStream fos = new FileOutputStream(file);
//从Client读,并写到Server硬盘
byte[] bbuf = new byte[1024];
int len;
while((len=URLis.read(bbuf))!=-1){
fos.write(bbuf,0,len);
}
URLis.close();
fos.close();
}
}