Java Socket小案例(2) 上传文本

需求:客户端从本地读取文本文件,上传到服务器,服务器收到后存在本地,并向客户端反馈信息

分析:

服务端:
源:网络输入流
目的:网络输出流、文本
操作的是文本,可以用字符流,同时提高效率,可以加缓冲

//服务端
public class UploadServer {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        PrintWriter pw = null;
        try {
            ss = new ServerSocket(6666);
            s = ss.accept();
            String ip = s.getInetAddress().getHostAddress();
            System.out.println(ip + "connected...");
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            pw = new PrintWriter(new FileWriter(
                    "D:/Java/javaCode/Inet/src/com/tcp1/1.java"), true);
            PrintWriter pwOut = new PrintWriter(new OutputStreamWriter(
                    s.getOutputStream()), true);
            String line = null;
            while ((line = bufIn.readLine()) != null) {
                pw.println(line);
            }
            pwOut.println("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
//客户端
public class UploadClient {
    public static void main(String[] args) {
        Socket s = null;
        BufferedReader bufr = null;
        try {
            s = new Socket("127.0.0.1", 6666);
            bufr = new BufferedReader(new InputStreamReader(
                    new FileInputStream(
                            "D:/Java/javaCode/Inet/src/com/tcp1/UploadClient.java")));
            PrintWriter pwOut = new PrintWriter(s.getOutputStream(), true);
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String line = null;
            while ((line = bufr.readLine()) != null) {
                pwOut.println(line);
            }
            s.shutdownOutput();
            line = bufIn.readLine();
            System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufr.close();
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

问题:

1.PrintWriter忘记写true
2.服务器读到了,但是客户端没有打印上传成功

原因

1.客户端读完文本之后,没有给一个结束标记,导致服务器还在等,以为上传没有成功

总结

1.读文本读得到回车

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值