Java简易服务器中文乱码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class DemoTCPServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6667);//构造服务器
while (true) {
Socket iouse01 = ss.accept();//服务器保持监听状态
new Thread(new Runnable() {//每加载一次图片创建一个线程
@Override
public void run() {
try {
InputStream ips = iouse01.getInputStream();//接收客户端请求的字节流
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader bis = new BufferedReader(ipsr);//将接收的字节流转换为字符流并缓冲
//获取客户端请求路径
String s = bis.readLine();
System.out.println(s);
String[] arr = s.split(" ");
String htmlpath = arr[1].substring(1);
FileInputStream fis = new FileInputStream(htmlpath);//本地字节流读取硬盘字节数据
OutputStream ops = iouse01.getOutputStream();//获取网络输出流对象
//HTTP固定请求头代码
ops.write("HTTP/1.1 200 OK\r\n".getBytes());
// 解决方法:正确告诉浏览器发送的内容是什么编码的
ops.write("Content-Type:text/html\r\n".getBytes());
ops.write("\r\n".getBytes());
//读取本地目的文件并输出
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
ops.write(bytes, 0, len);
}
fis.close();
iouse01.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}