• Java网络编程(TCP协议-练习-上传文本文件)


    客户端:

     1 package WebProgramingDemo;
     2 
     3 import java.io.BufferedReader;
     4 
     5 public class UploadTextClient {
     6 
     7     /**
     8      * @param args
     9      * @throws IOException
    10      * @throws UnknownHostException
    11      */
    12     public static void main(String[] args) throws UnknownHostException,
    13             IOException {
    14 
    15         Socket s = new Socket("192.168.2.103", 10005);
    16         BufferedReader bufr = new BufferedReader(new FileReader("client.txt"));
    17         PrintWriter out = new PrintWriter(s.getOutputStream(), true);
    18         String line = null;
    19         while ((line = bufr.readLine()) != null) {
    20             out.println(line);
    21 
    22         }
    23         s.shutdownOutput();
    24         BufferedReader bufIn = new BufferedReader(new InputStreamReader(
    25                 s.getInputStream()));
    26         String str = bufIn.readLine();
    27         System.out.println(str);
    28         bufr.close();
    29         s.close();
    30 
    31     }
    32 
    33 }

    服务端:

     1 package WebProgramingDemo;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.BufferedWriter;
     5 import java.io.FileWriter;
     6 import java.io.IOException;
     7 import java.io.InputStreamReader;
     8 import java.io.PrintWriter;
     9 import java.net.ServerSocket;
    10 import java.net.Socket;
    11 
    12 public class UploadTextServer {
    13 
    14     /**
    15      * @param args
    16      * @throws IOException
    17      */
    18     public static void main(String[] args) throws IOException {
    19 
    20         ServerSocket ss = new ServerSocket(10005);
    21         Socket s = ss.accept();
    22         System.out.println(s.getInetAddress().getHostAddress()
    23                 + ".....connected");
    24 
    25         BufferedReader bufIn = new BufferedReader(new InputStreamReader(
    26                 s.getInputStream()));
    27         BufferedWriter bufw = new BufferedWriter(new FileWriter("server.txt"));
    28         String line = null;
    29         while ((line = bufIn.readLine()) != null) {
    30             bufw.write(line);
    31             bufw.newLine();
    32             bufw.flush();
    33         }
    34         PrintWriter out = new PrintWriter(s.getOutputStream(), true);
    35         out.println("上传成功");
    36         bufw.close();
    37         s.close();
    38         ss.close();
    39     }
    40 
    41 }
  • 相关阅读:
    547. Friend Circles
    399. Evaluate Division
    684. Redundant Connection
    327. Count of Range Sum
    LeetCode 130 被围绕的区域
    LeetCode 696 计数二进制子串
    LeetCode 116 填充每个节点的下一个右侧节点
    LeetCode 101 对称二叉树
    LeetCode 111 二叉树最小深度
    LeetCode 59 螺旋矩阵II
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5324205.html
Copyright © 2020-2023  润新知