本帖最后由 wenbaoxing 于 2013-11-1 22:11 编辑
这是我写的没有try语句的代码,请高人指点,O(∩_∩)O谢谢!!!- import java.io.*;
- import java.net.*;
- //定义传送文件的客户端
- class CopyClient
- {
- public static void main(String[] args) throws Exception
- {
- Socket s=new Socket("192.168.1.105",10005);
- //定义源,创建文件读取流,读取硬盘中的文件
- BufferedReader bufr=new BufferedReader(new FileReader("IPDemo.java"));
- //获取客户端的输出流对象,以便将数据写入socket流中,让服务端读取,用PrintWriter太爽了
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
- String line=null;
- while((line=bufr.readLine())!=null)
- {
- out.println(line);
- }
- //读取完毕,关闭客户端的输出流
- s.shutdownOutput();
- //读取服务端的反馈信息
- BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
- String str=bufIn.readLine();
- System.out.println("Server说:"+str);
- //关闭资源
- bufr.close();
- s.close();
- }
- }
- //定义服务端
- class CopyServer
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss=new ServerSocket(10005);
- //获取客户端对象,并打印ip
- Socket s=ss.accept();
- String ip=s.getInetAddress().getHostAddress();
- System.out.println(ip+".........connected");
- //创建文件输出流接收客户端发送的文件将其写入本地硬盘,真正开发是需要客户端先将文件名称发送过来的
- BufferedWriter bufOut=new BufferedWriter(new FileWriter("sever.txt"));
- //获取客户端的字节输入流
- BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
- String line=null;
- while ((line=bufIn.readLine())!=null)
- {
- bufOut.write(line);
- bufOut.newLine();
- bufOut.flush();
- }
- //创建写入流给客户端反馈信息
- BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- out.write("文件上传成功");
- //out.newLine();
- out.flush();
- //关闭资源
- s.close();
- ss.close();
- }
- }
复制代码 |