server
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using DataBase;
namespace WebServer
{
class Program
{
private static int count = 0;
static HttpListener httpobj;
static void Main(string[] args)
{
httpobj = new HttpListener();
httpobj.Prefixes.Add("http://127.0.0.1:8080/myJson/");
httpobj.Start();
httpobj.BeginGetContext(Result, null);
Console.WriteLine($"服务端初始化完毕,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");
Console.ReadKey();
}
private static void Result(IAsyncResult ar)
{
httpobj.BeginGetContext(Result, null);
var guid = Guid.NewGuid().ToString();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"接到第{++count}个请求:{guid},时间:{DateTime.Now.ToString()}");
var context = httpobj.EndGetContext(ar);
var request = context.Request;
var response = context.Response;
context.Response.ContentType = "text/plain;charset=UTF-8";
context.Response.AddHeader("Content-type", "text/plain");
context.Response.ContentEncoding = Encoding.UTF8;
string returnObj = null;
if ( request.InputStream != null)
{
returnObj = HandleRequest(request, response);
}
else
{
returnObj = $"不是post请求或者传过来的数据为空";
}
var returnByteArr = Encoding.UTF8.GetBytes(returnObj);
#region 编辑需要返回的信息
ReturnData returnData = new ReturnData();
LevelPosInfo levelPosInfo = new LevelPosInfo();
levelPosInfo.LevelInfo = 1;
levelPosInfo.hight = 50;
Vector3 v1 = new Vector3(100,300,0);
levelPosInfo.posInfos.Add(v1);
returnData.LevelPosInfos.Add(levelPosInfo);
#endregion
var returnJson = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(returnData));
try
{
using (var stream = response.OutputStream)
{
stream.Write(returnJson, 0, returnJson.Length);
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"网络蹦了:{ex.ToString()}");
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"请求处理完成:{guid},时间:{DateTime.Now.ToString()}\r\n");
}
private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
{
string data = null;
try
{
var byteList = new List<byte>();
var byteArr = new byte[2048];
int readLen = 0;
int len = 0;
do
{
readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
len += readLen;
byteList.AddRange(byteArr);
} while (readLen != 0);
data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);
Console.WriteLine($"收到数据:{data}");
}
catch (Exception ex)
{
response.StatusDescription = "404";
response.StatusCode = 404;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
return $"在接收数据时发生错误:{ex.ToString()}";
}
response.StatusDescription = "200";
response.StatusCode = 200;
Console.ForegroundColor = ConsoleColor.Green;
var a = request.QueryString["id"];
Console.WriteLine($"客户端通过{request.HttpMethod}方式发来的数据:{data},参数:{request.QueryString["id"]}时间:{DateTime.Now.ToString()}");
return $"接收数据完成";
}
public static string GetJsonFile(string jsonfile)
{
string jsonstr = "";
using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o = (JObject)JToken.ReadFrom(reader);
jsonstr = o.ToString(Formatting.None);
}
}
return jsonstr;
}
}
}
client
using Newtonsoft.Json;
using DataBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
string operation;
do
{
Console.WriteLine("按任意键请求连接发送数据到服务端");
string flag = Console.ReadLine();
var url = "http://127.0.0.1:8080/myJson?id=100";
Console.WriteLine($"请求服务地址:{url},时间:{DateTime.Now.ToString()}");
Data data = new Data();
var jsonModel = JsonConvert.SerializeObject(data);
Post(url, jsonModel);
Console.WriteLine($"请问是否继续:继续 【y】,退出【n】");
operation = Console.ReadLine();
} while (operation == "y");
}
public static string Post(string Url, string jsonParas)
{
string strURL = Url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string paraUrlCoded = jsonParas;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception)
{
writer = null;
Console.Write("连接服务器失败!");
}
writer.Write(payload, 0, payload.Length);
writer.Close();
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"服务端返回信息:{postContent},时间:{DateTime.Now.ToString()}");
return postContent;
}
}
}
class Data
{
public string Name;
public int years;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)