Java socket简单服务端客户端

该博客展示了如何使用Java的Socket编程创建一个简单的服务器,监听8080端口,并处理客户端的HTTP请求。当客户端连接时,服务器读取请求并根据请求内容返回不同的HTTP响应。如果请求合法,服务器会发送一个HTML文件的内容,否则发送404错误。
摘要由CSDN通过智能技术生成

Java socket简单服务端客户端

package com.www.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author 47144
 */
public class ServerDemo {


    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("serverSocket is running");
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("connected from "+socket.getRemoteSocketAddress());
                Thread t = new Handle(socket);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

class Handle extends Thread{

    private Socket socket;

    public Handle(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream inputStream = this.socket.getInputStream()) {
            try (OutputStream outputStream = this.socket.getOutputStream()) {
                handle(inputStream, outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                this.socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("client disconnected!");
        }
    }

    private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,StandardCharsets.UTF_8));
        // 读取http请求
        boolean requestOk = false;
        String firstLine = bufferedReader.readLine();
        if (firstLine.startsWith("GET / HTTP/1.")){
            requestOk= true;
        }
        for (;;){
            String header = bufferedReader.readLine();
            if (header.isEmpty()){
                break;
            }
            System.out.println(header);
        }

        System.out.println(requestOk?"Response OK":"Response ERROR");

        if (!requestOk){

            bufferedWriter.write("HTTP/1.0 404 Not Found\r\n");
            bufferedWriter.write("Content-Length: 0\r\n");
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();
        }else {

            BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\47144\\IdeaProjects\\mybatiStudy\\mybatis-01\\src\\main\\java\\com\\www\\socket\\a.html"));
            StringBuilder data = new StringBuilder();
            String line = null;
            while ((line=reader.readLine())!=null){
                data.append(line);
            }
            reader.close();
            int length = data.toString().getBytes(StandardCharsets.UTF_8).length;

            bufferedWriter.write("HTTP/1.1 200 OK\r\n");
            bufferedWriter.write("Connection: keep-alive OK\r\n");
            bufferedWriter.write("Content-Type: text/html\r\n");
            bufferedWriter.write("Content-Length: "+length+"\r\n");
            bufferedWriter.write("\r\n");
            bufferedWriter.write(data.toString());
            data.delete(0,data.length());
            bufferedWriter.flush();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值