我正在制作一个简单的 Web 服务器,每次客户端连接时都会在其中生成一个新线程。然后我需要使用 BufferedOutputStream 发送响应(因为 HTTP 协议需要 /r/n 在行尾)。这是我的代码:
class HttpServer{
public static void main(String args[]){
ServerSocket ss = null;
int port = 40000;
try{
if(args.length > 0){
port = Integer.parseInt(args[0]);
}
ss = new ServerSocket(port);
while(true){
Socket client = ss.accept();
User user = new User(client);
user.start();
}
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
}
我的用户类:
class User extends Thread{
Socket client;
public User(Socket s){
client = s;
}
public void run(){
try{
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
println(bos, "Hello World");
bos.close();
client.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i=0; i<array.length; i++){
bos.write(array[i]);
}
return;
}
}
当我尝试创建 BufferedOutputStream 时出现问题;它给了我一个“套接字已关闭”错误,我不知道为什么。
任何帮助将非常感激。
谢谢!
这是不起作用的代码:
class User extends Thread{
Socket client;
public User(Socket s){
client = s;
}
public void run(){
try{
System.out.println("Address: " + client.getInetAddress().toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
Boolean first = true;
while(!((line = reader.readLine()).equals(""))){
if(first)
System.out.println(line.split(" ")[1]);
first = false;
}
reader.close();
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
println(bos, "Hello World");
bos.close();
// Close socket
client.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i=0; i<array.length; i++){
bos.write(array[i]);
}
return;
}
}