server
//服务器
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
//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)
{
//提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
httpobj = new HttpListener();
//定义url及端口号,通常设置为配置文件
httpobj.Prefixes.Add("http://127.0.0.1:8080/myJson/");
//启动监听器
httpobj.Start();
//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
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()}");
//获得context对象
var context = httpobj.EndGetContext(ar);
var request = context.Request;
var response = context.Response;
//如果是js的ajax请求,还可以设置跨域的ip地址与参数
//context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件
//context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件
//context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件
context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
context.Response.ContentEncoding = Encoding.UTF8;
string returnObj = null;//定义返回客户端的信息
if (/*request.HttpMethod == "POST" &&*/ request.InputStream != null)
{
//处理客户端发送的请求并返回处理信息
returnObj = HandleRequest(request, response);
}
else
{
returnObj = $"不是post请求或者传过来的数据为空";
}
var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
//var returnJson = Encoding.UTF8.GetBytes(GetJsonFile("../../../BerthEdges.json"));//设置客户端返回信息的编码
#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
//levelPosInfo.posInfos.add(posInfo);
var returnJson = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(returnData));//设置客户端返回信息的编码
try
{
using (var stream = response.OutputStream)
{
//把处理信息返回到客户端
stream.Write(returnJson, 0, returnJson.Length);
//stream.Write(returnByteArr, 0, returnByteArr.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}");
//获取得到数据data可以进行其他操作
}
catch (Exception ex)
{
response.StatusDescription = "404";
response.StatusCode = 404;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考
}
response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
Console.ForegroundColor = ConsoleColor.Green;
var a = request.QueryString["id"];//获取客户端发送过来的参数
Console.WriteLine($"客户端通过{request.HttpMethod}方式发来的数据:{data},参数:{request.QueryString["id"]}时间:{DateTime.Now.ToString()}");
return $"接收数据完成";
}
//读取json文件
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);//格式化输出Json用Formatting.Indented
}
}
return jsonstr;
}
}
//同步阻塞
//class Program
//{
// delegate int GuangChaoshi(int a);
// static void Main(string[] args)
// {
// string ss2 = GetJsonFile("../../../BerthEdges.json");
// HttpListener httpListener = new HttpListener();
// if (!HttpListener.IsSupported)
// {
// throw new System.InvalidOperationException(
// "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
// }
// httpListener.Prefixes.Add("http://127.0.0.1/TiKuSync/");//
// httpListener.Start();
// Console.WriteLine("监听中...");
// try
// {
// ThreadPool.SetMinThreads(8, 5);
// ThreadPool.SetMaxThreads(100, 30);
// while (true)
// {
// try
// {
// HttpListenerContext context = httpListener.GetContext();//相当于accept() ,同步阻塞
// ThreadPool.QueueUserWorkItem((o) => { Handler(context); });
// if (Console.KeyAvailable)
// break;
// }
// catch (HttpListenerException exception)
// {
// Console.WriteLine(exception.Message);
// break;
// }
// catch (InvalidOperationException exception)
// {
// Console.WriteLine(exception.Message);
// break;
// }
// }
// }
// catch (Exception ex)
// {
// //if (httpListener.IsListening) { httpListener.Stop(); }
// Console.WriteLine(ex.Message);
// }
// Console.ReadLine();
// }
// private static int Counter = 0;
// private static void Handler(HttpListenerContext context)
// {
// try
// {
// Counter++;
// ///请求对象
// HttpListenerRequest request = context.Request;
// Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
// Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
// Console.WriteLine("Accept-Language: {0}",
// string.Join(",", request.UserLanguages));
// Console.WriteLine("User-Agent: {0}", request.UserAgent);
// Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
// Console.WriteLine("Connection: {0}",
// request.KeepAlive ? "Keep-Alive" : "close");
// Console.WriteLine("Host: {0}", request.UserHostName);
// Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
// ///回应对象
// HttpListenerResponse response = context.Response;
// string responseString = "This is HttpListener Service!请求: " + Counter + "";
// byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// response.ContentEncoding = Encoding.UTF8;
// response.ContentLength64 = buffer.Length;
// response.ContentType = "text/html; charset=UTF-8";
// response.KeepAlive = true;
// using (Stream output = response.OutputStream)
// {
// //output.Write(buffer, 0, buffer.Length);
// //output.Flush();
// System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
// writer.Write(responseString);
// // 必须关闭输出流
// writer.Close();
// }
// response.Close();
// }
// catch (Exception exception)
// {
// Console.WriteLine(exception.Message);
// }
// finally
// {
// Console.WriteLine("请求次数:{0}", Counter);
// }
// }
// //读取json文件
// 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();
// }
// }
// return jsonstr;
// }
}
client
using Newtonsoft.Json;
using DataBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
//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 wc = new System.Net.WebClient();
var url = "http://127.0.0.1:8080/myJson?id=100";
Console.WriteLine($"请求服务地址:{url},时间:{DateTime.Now.ToString()}");
//模拟一个json数据发送到服务端
Data data = new Data();
var jsonModel = JsonConvert.SerializeObject(data);
Post(url, jsonModel);
//jsonModel = "发一个json文件";
//发送到服务端并获得返回值
//wc.UploadData(url, Encoding.UTF8.GetBytes(jsonModel));//post
//var returnInfo = wc.DownloadData(url); //get
把服务端返回的信息转成字符串
//var str = Encoding.UTF8.GetString(returnInfo);
//Console.ForegroundColor = ConsoleColor.Cyan;
//Console.WriteLine($"服务端返回信息:{str},时间:{DateTime.Now.ToString()}");
//Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"请问是否继续:继续 【y】,退出【n】");
operation = Console.ReadLine();
} while (operation == "y");
}
public static string Post(string Url, string jsonParas)
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//设置参数,并进行URL编码
string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
// String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
// Stream postData = Request.InputStream;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"服务端返回信息:{postContent},时间:{DateTime.Now.ToString()}");
return postContent;//返回Json数据
}
}
}
class Data
{
public string Name;
public int years;
}