- package day27;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedWriter;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class FileService {
- public static void main(String[] args) throws Exception {
- ServerSocket ss=new ServerSocket(10010);
- Socket s=ss.accept();
- String ip=s.getInetAddress().getHostAddress();
- BufferedInputStream bufin=new BufferedInputStream(s.getInputStream());
- BufferedOutputStream bufoFromSys=new BufferedOutputStream(new FileOutputStream("new.jpg"));
- BufferedWriter bufwToSc=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- byte[] buf=new byte[1024];
- int len=0;
- while ((len=bufin.read(buf))!=-1)
- {
- bufoFromSys.write(buf);
- bufoFromSys.flush();
- }
- bufwToSc.write("恭喜你上传成功");
- bufwToSc.newLine();
- ss.close();
- bufin.close();
- bufoFromSys.close();
- bufwToSc.close();
- System.out.println(ip+"上传了一个文件");
- }
- }
复制代码- package day27;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.Socket;
- import java.net.UnknownHostException;
- public class FileClient {
- public static void main(String[] args) throws UnknownHostException, IOException {
- Socket sc=new Socket("10.7.74.7", 10010);
- BufferedInputStream bufinFromSys=new BufferedInputStream(new FileInputStream("pic1.jpg"));
- BufferedOutputStream bufo=new BufferedOutputStream(sc.getOutputStream());
- BufferedReader bufrFromSc=new BufferedReader(new InputStreamReader(sc.getInputStream()));
- byte[] buf=new byte[1024];
- int len=0;
- while ((len=bufinFromSys.read(buf))!=-1)
- {
- bufo.write(buf, 0, len);
- bufo.flush();
- }
- sc.shutdownOutput();
- String str=bufrFromSc.readLine();
- //if (str.contains("恭喜"))
- //System.out.println("上传成功");
- System.out.println(str);
-
- sc.close();
- bufo.close();
- bufinFromSys.close();
- }
- }
复制代码 一运行就报错啊:
Exception in thread "main" java.net.SocketException: Socket closed
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:116)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:316)
at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
at java.io.BufferedWriter.close(BufferedWriter.java:266)
at day27.FileService.main(FileService.java:31)
不知道什么问题,Socket closed 端口关闭 这也太难懂了吧
|
|