需求:客户端从本地读取文本文件,上传到服务器,服务器收到后存在本地,并向客户端反馈信息
分析:
服务端:
源:网络输入流
目的:网络输出流、文本
操作的是文本,可以用字符流,同时提高效率,可以加缓冲
//服务端
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.读文本读得到回车