TCP通信程序练习 需求:多线程来实现文件上传,文件传输完成有返回 客户端程序 [Java] 纯文本查看 复制代码 package com.itheima01;
import java.io.*;
import java.net.Socket;
public class FileStocket {
public static void main(String[] args) throws IOException {
Socket s = new Socket("192.168.14.24", 2019);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\itcast.txt"),"GBK"));//GBK--UTF-8
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));// 8bits -- UTF-8
String str;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
bw.flush();
}
s.shutdownOutput();
BufferedReader br1 = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("服务端反馈:" + br1.readLine());
s.close();
br.close();
}
}
服务端程序 [Java] 纯文本查看 复制代码 package com.itheima02;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Test03 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(2019);
while (true){
Socket s = ss.accept();
Thread t = new Thread(new Test04(s));
t.start();
}
}
}
[Java] 纯文本查看 复制代码 package com.itheima02;
import java.io.*;
import java.net.Socket;
public class Test04 implements Runnable{
private Socket s;
//constructor
public Test04(Socket s ){
this.s = s;
}
@Override
public void run() {
int count = 0;
while (true){
File file = new File("D:\\itcast["+count+"].txt");
if(!file.exists()){
break;
}
count++;
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\itcast["+count+"].txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while ((line = br.readLine())!= null){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw1.write("文件传输完成!");
bw1.newLine();
bw1.flush();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
传输的文件乱码问题分析: 在客户端程序中先将文件的字符按默认的字符集GBK解码,缓冲字符流使用new FileReader()的构造方法,使用的是默认字符集UTF-8编码成字符流,包装完成的字符流和原来的文件的字符流已经不一样了,此时一定会乱码。要解决这个问题,就要在编码时指定编码集,采用InputStreamReader(InputStream in , String charsetname)的构造方法来构造字符流。 [Java] 纯文本查看 复制代码 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\itcast.txt"),"GBK"));
|