- public class UpLoadServer
- {
- public static void main(String[] args) throws Exception
- {
- //创建服务器端套接字监听指定端口
- ServerSocket server = new ServerSocket(11111);
- //获取连接的客户端套接字,并显示连接成功
- Socket client = server.accept();
- String ip = client.getInetAddress().getHostAddress();
- System.out.println(ip+" 连接成功!");
- //获取客户端套接字输入流,接收客户端上传的数据
- BufferedInputStream bufIn =
- new BufferedInputStream(client.getInputStream());
-
- //定义缓冲区输出流,向服务器端写数据
- BufferedOutputStream bufOut =
- new BufferedOutputStream(new FileOutputStream("d:\\heima_server.jpg"));
- //将客户端上传的数据存储在服务器端
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len = bufIn.read(buf))!=-1)
- {
- bufOut.write(buf,0,len);
- }
- //上传完成后,向客户端反馈传输结果
- OutputStream out = client.getOutputStream();
- out.write("上传成功!".getBytes());
- //关闭资源
- bufOut.close();
- client.close();
- server.close();
- }
- }
- public class UpLoadClient {
- public static void main(String[] args) throws Exception
- {
- //在建立客户端套接字连接到指定服务器端
- Socket client = new Socket("192.168.100.4",11111);
- //用字节缓冲区对象读取本地的文件
- BufferedInputStream bufIn =
- new BufferedInputStream(new FileInputStream("D:\\heima.jpg"));
-
- //获取客户端套接字的输出流,向服务器端上传数据
- BufferedOutputStream bufOut =
- new BufferedOutputStream(client.getOutputStream());
- //将本地文件上传到服务器端
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len = bufIn.read(buf))!=-1)
- {
- bufOut.write(buf,0,len);
- }
-
- //文件上传完毕,关闭输出流
- client.shutdownOutput();
- //获取客户端套接字输入流,接收服务器端反馈信息
- InputStream in = client.getInputStream();
- byte[] result = new byte[1024];
- int num = in.read(result);
- System.out.println(new String(result,0,num));
- //关闭资源
- bufIn.close();
- client.close();
- }
- }
复制代码
|
|