using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
public class TestServerHttp : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        ListenAsync();
    }

    private HttpListener listener;
    // Update is called once per frame
    async void ListenAsync()
    {
        try
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            string localIp = "";
            foreach (var ip in ipEntry.AddressList)
            {
                Debug.Log("IP Address: " + ip.ToString());
                localIp = ip.ToString();
            }
            listener = new HttpListener();
            //string url1 = string.Format($"http://{localIp}:51111/MyApp/");
            string url2 = string.Format($"http://{localIp}:51111/MyApp/aa/");
            string url3 = string.Format($"http://{localIp}:51111/MyApp/bb/");
            Debug.Log("IP url: " + url2);
            listener.Prefixes.Add(url2);
            listener.Prefixes.Add(url2);
            listener.Prefixes.Add(url3);
            //listener.Prefixes.Add("http://localhost}:51111/wangermazi/");
            listener.Start();
            while (true)
            {
                HttpListenerContext context = await listener.GetContextAsync();
                Dictionary<string, object> res = new Dictionary<string, object>();
                res["succ"] = true;
                res["content"] = "hah";
                var item = MiniJSON.Json.Serialize(res);
                Debug.Log(item);
                //string msg = "You asked for: " + context.Request.RawUrl + Time.realtimeSinceStartup;
                var msg = item;
                context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                Debug.Log(context.Request.Url + "  " + context.Request.RemoteEndPoint.Address);
                Debug.Log("HttpMethod" + context.Request.HttpMethod);
                if (context.Request.HasEntityBody)
                {
                    Stream SourceStream = context.Request.InputStream;
                    byte[] currentChunk = ReadLineAsBytes(SourceStream);
                    //获取数据中有空白符需要去掉,输出的就是post请求的参数字符串 如:username=linezero
                    var length = context.Request.Headers["Content-Length"];
                    //var temp = Encoding.Default.GetString(currentChunk,0,int.Parse(length));
                    var temp = ReadString(context);
                    //byte last = currentChunk[int.Parse(length) + 1];
                    //Debug.Log("---" + currentChunk.Length);
                    Debug.Log("---" + length);
                    //Debug.Log("---" + last);
                    Debug.Log("temp" + temp);
                    byte[] buffer = new byte[1];
                    Debug.Log("buffer" + buffer[0]);
                }
                Debug.Log("QueryString  " + context.Request.QueryString);
                Debug.Log("name " + context.Request.QueryString["name"]);
                Debug.Log("City " + context.Request.Headers["City"]);
                using (Stream s = context.Response.OutputStream)
                {
                    using (StreamWriter writer = new StreamWriter(s))
                    {
                        await writer.WriteAsync(msg);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log("ListenAsync: " + e);
            listener.Stop();
        }

        //
    }

    private void OnDestroy()
    {
        if (listener != null)
        {
            listener.Stop();
        }
    }
    
    
    static byte[] ReadLineAsBytes(Stream SourceStream)
    {
        var resultStream = new MemoryStream();
        while (true)
        {
            int data = SourceStream.ReadByte();
            if (data > 0)
            {
                resultStream.WriteByte((byte)data);
            }
            else
            {
                break;
            }
        }
        resultStream.Position = 0;
        byte[] dataBytes = new byte[resultStream.Length];
        resultStream.Read(dataBytes, 0, dataBytes.Length);
        return dataBytes;
    }

    static string ReadString(HttpListenerContext context)
    {
        using (Stream inputStream = context.Request.InputStream)
        using (StreamReader reader = new StreamReader(inputStream))
        {
            string json = reader.ReadToEnd();
            return json;
        }
    }
}

  iOS 代码

 

-(void)httGetSync{
    NSString *urlString = @"http://192.168.6.31:51111/MyApp/?name=wangwu";
    //NSCharacterSet *customAllowedSet =  NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet;
    //NSCharacterSet *customAllowedSet = [[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+-./:;=?@_~%#[]"] invertedSet];
    NSCharacterSet *customAllowedSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *urlstr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:customAllowedSet];
    NSURL *url = [NSURL URLWithString:urlstr];
    
    NSLog(@"%@",url);
    
    //NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
    NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
    [req setHTTPMethod:@"GET"];
    
    NSString *getString = @"";
    NSData *getdata = [getString dataUsingEncoding:NSUTF8StringEncoding];
    [req setValue:@"wangermazi" forHTTPHeaderField:@"City"];
    
    NSLog(@"Curr thread %@",[NSThread currentThread]);
    
    NSURLSession *shareSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [shareSession dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data && error == nil){
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
            NSLog(@"Curr thread %@",[NSThread currentThread]);
        }
    }];
    
    [dataTask resume];
}


-(void)httpPostSync11{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://192.168.6.31:51111/MyApp/"]];
    //[request setHTTPMethod:@"GET"];
    [request setHTTPMethod:@"POST"];
    NSString* postString = [NSString stringWithFormat:@"n=%@&c=%@", @"w" ,@"b"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    //NSData *poData = [postString dataUsingEncoding:NSUTF8StringEncoding]
    //[request setHTTPBody:poData];
    NSURLSession *shareSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [shareSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data && error == nil){
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
    [dataTask resume];
}

 

 posted on 2023-02-14 11:45  1039781968  阅读(30)  评论(0)    收藏  举报