创建简单http服务器

const http = require("http");
let server = http.createServer(function (req, res){
    console.log("req received");
    res.writeHead(200,{"Content-Type":'text/plain'});
    res.end("Hello");
})
server.listen(3000,'127.0.0.1');
console.log("server started on localhost port 3000");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用C#创建简单HttpListener服务器的示例代码: ```csharp using System; using System.Net; using System.Text; public class SimpleHttpServer { public static void Main(string[] args) { // 设置监听的地址和端口号 string url = "http://localhost:8080/"; // 创建HttpListener对象 HttpListener listener = new HttpListener(); // 添加要监听的地址 listener.Prefixes.Add(url); // 开始监听 listener.Start(); Console.WriteLine("Server is running..."); while (true) { // 等待客户端请求 HttpListenerContext context = listener.GetContext(); // 获取请求对象 HttpListenerRequest request = context.Request; // 获取请求的HTTP方法(GET, POST等) string httpMethod = request.HttpMethod; // 获取请求的URL string urlRequest = request.Url.ToString(); // 获取请求的内容 string requestBody = new System.IO.StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd(); // 构建响应内容 string responseBody = "<html><body><h1>Hello, World!</h1></body></html>"; // 将响应内容转换为字节数组 byte[] buffer = Encoding.UTF8.GetBytes(responseBody); // 设置响应状态码 context.Response.StatusCode = 200; // 设置响应内容长度 context.Response.ContentLength64 = buffer.Length; // 发送响应内容 context.Response.OutputStream.Write(buffer, 0, buffer.Length); // 关闭响应 context.Response.OutputStream.Close(); } } } ``` 这个例子创建一个HttpListener对象,并设置要监听的地址和端口号。然后使用while循环等待客户端请求。当有客户端请求到达时,它获取请求对象,并从请求对象中获取HTTP方法,URL和内容。然后构建响应内容,并将其发送回客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值