Форум программистов, компьютерный форум, киберфорум
C#: Веб-сервисы и WCF
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
2 / 2 / 0
Регистрация: 19.10.2015
Сообщений: 19
1

HTTPClient и HTTPServer Serialization Error! Help

12.12.2019, 14:44. Показов 1800. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Есть 2 программы HTTPClient и HTTPServer.
Запускаем сервер указываем порт, потом запускаем клиента и по этому порту можно отдавать команды /Ping и тд...
Но ничего не происходит. выдаёт ошибку "SerializationException: Ожидается элемент "root"" на стороне клиента
Кликните здесь для просмотра всего текста

Клиент должен уметь кидать запросы на сервер с адресом http://127.0.0.1:{port}/{method} , где port – целоче
число, приходит первой строкой со стандартного потока ввода, а method – вызываемый на сервере метод.
Далее расписаны поддерживаемые сервером методы.
/Ping
Метод пинг служит признаком того, что сервер находится в рабочем состоянии, в ответе запроса приходит
HttpStatusCode.Ok (200). В любом другом случае сервер считается недоступным.
/GetInputData
С помощью этого метода участник может получить входные данные для задачи. Входные данные приходят
в теле ответа в виде сериализованного в Json объекта типа Input в кодировке Utf-8.
/WriteAnswer
С помощью этого метода можно отдать ответ задачи серверу. Ответ нужно отдавать в теле запроса в виде
сериализованного объекта Output в Json в кодировке Utf-8.


HttpClient
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization.Formatters;
using System.Net;
using System.Globalization;
using System.Threading;
 
namespace client
{
    [DataContract]
    public class Input
    {
        [DataMember]
        public int K { get; set; }
        [DataMember]
        public decimal[] Sums { get; set; }
        [DataMember]
        public int[] Muls { get; set; }
    }
    [DataContract]
    public class Output
    {
        [DataMember]
        public decimal SumResult { get; set; }
        [DataMember]
        public int MulResult { get; set; }
        [DataMember]
        public decimal[] SortedInputs { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int port = Int32.Parse(Console.ReadLine());
            Input input;
            bool ready = false;
            while (!ready)
            {
                ready = Ping(port) == HttpStatusCode.OK;
                Thread.Sleep(100);
            }
            string s2 = GetInputData(port);
            //десериализация входных данных
            DataContractJsonSerializer formatteri = new DataContractJsonSerializer(typeof(Input));
            MemoryStream ms = new MemoryStream(Encoding.GetEncoding("UTF-8").GetBytes(s2));
            input = (Input)formatteri.ReadObject(ms);
            //их обработка
            Output output = process(input);
            //сериализация
            string s3 = MyJsonSerialize(output);
            //и отправка серверу
            WriteAnswer(port, s3);
        }
        //преобразование числа в строку минимум с одним знаком после точки
        static string FormatDecimal(decimal a)
        {
            string r;
            decimal d = a - Decimal.Truncate(a);
            r = a.ToString("G", CultureInfo.InvariantCulture);
            if (d == 0)
            {
                r = r + ".0";
            }
            return r;
        }
        //сериализация объекта
        static string MyJsonSerialize(Output output)
        {
            //сериализация массива
            StringBuilder arr = new StringBuilder();
            for (int i = 0; i < output.SortedInputs.Length; i++)
            {
                arr.Append(FormatDecimal(output.SortedInputs[i]));
                if (i != output.SortedInputs.Length - 1)
                    arr.Append(",");
            }
            return "{" + String.Format("\"SumResult\":{0},\"MulResult\":{1},\"SortedInputs\":[{2}]", FormatDecimal(output.SumResult), output.MulResult, arr.ToString()) + "}";
        }
        //обработка данных
        static Output process(Input input)
        {
            Output output = new Output();
            //сумма всех чисел из массива Sums входного объекта, умноженная на коэффициент K
            output.SumResult = 0;
            output.SortedInputs = new decimal[input.Muls.Length + input.Sums.Length];
            int idx = 0;
            foreach (decimal i in input.Sums)
            {
                output.SortedInputs[idx] = i;
                idx++;
                output.SumResult += i;
            }
            //умножаем сумму на К
            output.SumResult *= input.K;
            //MulResult произведение всех чисел из массива Muls входного обекта
            output.MulResult = 1;
            foreach (int i in input.Muls)
            {
                output.SortedInputs[idx] = i;
                idx++;
                output.MulResult *= i;
            }
            //SortedInputs отсортированные числа из полей Sums, Muls входного объекта
            //сортировка массива
            Array.Sort(output.SortedInputs);
            return output;
        }
        //отправка запроса на сервер
        static string Send(string url, string method, string contenttype, byte[] content, out HttpStatusCode code)
        {
            string useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
            string accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            string AcceptCharset = "Accept-Charset=windows-1251,utf-8;q=0.7,*;q=0.7";
            string AcceptLanguage = "ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3";
 
            string txt = "";
            try
            {
                Uri uri = new Uri(url);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                req.ContentType = @"text/html; charset=utf-8";
 
                req.AllowAutoRedirect = true;
                req.UserAgent = useragent;
                req.Accept = accept;
                req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                req.Headers.Add(HttpRequestHeader.AcceptLanguage, AcceptLanguage);
                req.Headers.Add(HttpRequestHeader.AcceptCharset, AcceptCharset);
                //Для POST-запроса
                if (method == "POST")
                {
                    req.Method = method;
                    req.ContentType = contenttype;
                    req.ContentLength = content.Length;
                    req.GetRequestStream().Write(content, 0, content.Length);
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
 
                StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.Default);
                txt = reader.ReadToEnd();
                reader.Close();
                code = resp.StatusCode;
            }
            catch (Exception ex)
            {
                code = HttpStatusCode.InternalServerError;
            }
            return txt;
        }
        //посылка GET-запроса
        static string Get(string url, out HttpStatusCode code)
        {
            return Send(url, "GET", "", new byte[0], out code);
        }
        //посылка POST-запроса
        static string Post(string url, string postdata, out HttpStatusCode code)
        {
            byte[] ByteArr = Encoding.GetEncoding("UTF-8").GetBytes(postdata);  //кодирование отправляемых данных
            return Send(url, "POST", "application/x-www-form-urlencoded", ByteArr, out code);
        }
        /*Метод пинг служит признаком того, что сервер находится в рабочем состоянии, в ответе запроса приходит
HttpStatusCode.Ok (200). В любом другом случае сервер считается недоступным.*/
        static HttpStatusCode Ping(int port)
        {
            HttpStatusCode r;
            string url = String.Format("http://127.0.0.1:{0}/Ping", port);
            Get(url, out r);
            return r;
        }
        /*С помощью этого метода участник может получить входные данные для задачи. Входные данные приходят
в теле ответа в виде сериализованного в Json объекта типа Input в кодировке Utf-8.*/
        static string GetInputData(int port)
        {
            HttpStatusCode r;
            string url = String.Format("http://127.0.0.1:{0}/GetInputData", port);
            return Get(url, out r);
        }
        /*С помощью этого метода можно отдать ответ задачи серверу. Ответ нужно отдавать в теле запроса в виде
сериализованного объекта Output в Json в кодировке Utf-8.*/
        static HttpStatusCode WriteAnswer(int port, string data)
        {
            HttpStatusCode r;
            string url = String.Format("http://127.0.0.1:{0}/WriteAnswer", port);
            Post(url, data, out r);
            return r;
        }
 
    }
}
HTTPServer
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Globalization;
 
namespace server
{
    [DataContract]
    public class Input
    {
        [DataMember]
        public int K { get; set; }
        [DataMember]
        public decimal[] Sums { get; set; }
        [DataMember]
        public int[] Muls { get; set; }
    }
    [DataContract]
    public class Output
    {
        [DataMember]
        public decimal SumResult { get; set; }
        [DataMember]
        public int MulResult { get; set; }
        [DataMember]
        public decimal[] SortedInputs { get; set; }
    }
 
    class Program
    {
        static HttpListener server; //слушатель запросов
        static bool bStop = false;
 
        //преобразование числа в строку минимум с одним знаком после точки
        static string FormatDecimal(decimal a)
        {
            string r;
            decimal d = a - Decimal.Truncate(a);
            r = a.ToString("G", CultureInfo.InvariantCulture);
            if (d == 0)
            {
                r = r + ".0";
            }
            return r;
        }
        //сериализация объекта
        static string MyJsonSerialize(Output output)
        {
            //сериализация массива
            StringBuilder arr = new StringBuilder();
            for (int i = 0; i < output.SortedInputs.Length; i++)
            {
                arr.Append(FormatDecimal(output.SortedInputs[i]));
                if (i != output.SortedInputs.Length - 1)
                    arr.Append(",");
            }
            return "{" + String.Format("\"SumResult\":{0},\"MulResult\":{1},\"SortedInputs\":[{2}]", FormatDecimal(output.SumResult), output.MulResult, arr.ToString()) + "}";
        }
        //обработка данных
        static Output process(Input input)
        {
            Output output = new Output();
            //сумма всех чисел из массива Sums входного объекта, умноженная на коэффициент K
            output.SumResult = 0;
            output.SortedInputs = new decimal[input.Muls.Length + input.Sums.Length];
            int idx = 0;
            foreach (decimal i in input.Sums)
            {
                output.SortedInputs[idx] = i;
                idx++;
                output.SumResult += i;
            }
            //умножаем сумму на К
            output.SumResult *= input.K;
            //MulResult произведение всех чисел из массива Muls входного обекта
            output.MulResult = 1;
            foreach (int i in input.Muls)
            {
                output.SortedInputs[idx] = i;
                idx++;
                output.MulResult *= i;
            }
            //SortedInputs отсортированные числа из полей Sums, Muls входного объекта
            //сортировка массива
            Array.Sort(output.SortedInputs);
            return output;
        }
 
        static void Main(string[] args)
        {
            //port – целое число, приходит первой строкой со стандартного потока ввода
            int port = Int32.Parse(Console.ReadLine());
 
            Input input;
            Output output = null;
            server = new HttpListener(); // Создаем "слушателя" для указанного порта
            server.Prefixes.Add(String.Format("http://127.0.0.1:{0}/Ping/", port));
            server.Prefixes.Add(String.Format("http://127.0.0.1:{0}/PostInputData/", port));
            server.Prefixes.Add(String.Format("http://127.0.0.1:{0}/GetAnswer/", port));
            server.Prefixes.Add(String.Format("http://127.0.0.1:{0}/Stop/", port));
            server.Start(); // Запускаем его
 
 
            // В бесконечном цикле
            while (!bStop)
            {
                //ожидаем входящие запросы
                HttpListenerContext context = server.GetContext();
                //получаем входящий запрос
                HttpListenerRequest request = context.Request;
                /*Метод пинг служит признаком того, что сервер находится в рабочем состоянии, в ответе запроса приходит
HttpStatusCode.Ok (200). В любом другом случае сервер считается недоступным.*/
                if (request.RawUrl.ToUpper().Contains("PING"))
                {
                    string responseString = "";
                    HttpListenerResponse response = context.Response;
                    response.ContentType = "text/plain; charset=UTF-8";
                    response.StatusCode = 200;
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    using (Stream o = response.OutputStream)
                    {
                        o.Write(buffer, 0, buffer.Length);
                    }
                }
                /*С помощью этого метода сервер должен безопасно закончить свою работу, тем самым закончив исполнение
программы решения участника.*/
                else if (request.RawUrl.ToUpper().Contains("STOP"))
                {
                    string responseString = "";
                    HttpListenerResponse response = context.Response;
                    response.ContentType = "text/plain; charset=UTF-8";
                    response.StatusCode = 200;
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    using (Stream o = response.OutputStream)
                    {
                        o.Write(buffer, 0, buffer.Length);
                    }
                    bStop = true;
                }
                /*С помощью этого метода программа жюри посылает входные данные для задачи. Входные данные приходят
в теле запроса в виде сериализованного в Json объекта типа Input в кодировке Utf-8.*/
                else if (request.RawUrl.ToUpper().Contains("POSTINPUTDATA"))
                {
                    string s2;
                    using (Stream body = request.InputStream)
                    {
                        using (StreamReader reader = new StreamReader(body))
                        {
                            s2 = reader.ReadToEnd();
                        }
                    }
                    //десериализация входных данных
                    DataContractJsonSerializer formatteri = new DataContractJsonSerializer(typeof(Input));
                    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s2));
                    input = (Input)formatteri.ReadObject(ms);
                    //их обработка
                    output = process(input);
                    string responseString = "";
                    HttpListenerResponse response = context.Response;
                    response.ContentType = "text/plain; charset=UTF-8";
                    response.StatusCode = 200;
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    using (Stream o = response.OutputStream)
                    {
                        o.Write(buffer, 0, buffer.Length);
                    }
                }
                /*С помощью этого метода программа жюри запрашивает ответ задачи. Решение нужно отдавать в теле ответа
в виде сериализованного объекта Output в Json в кодировке Utf-8.*/
                else if (request.RawUrl.ToUpper().Contains("GETANSWER"))
                {
                    string responseString;
                    HttpListenerResponse response = context.Response;
                    response.ContentType = "text/plain; charset=UTF-8";
                    if (output != null)
                    {
                        //сериализация результата 
                        responseString = MyJsonSerialize(output);
                        response.StatusCode = 200;
                    }
                    else
                    {
                        responseString = "";
                        response.StatusCode = 403;
                    }
 
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    using (Stream o = response.OutputStream)
                    {
                        o.Write(buffer, 0, buffer.Length);
                    }
                }
            }
            server.Stop();
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
12.12.2019, 14:44
Ответы с готовыми решениями:

POST запрос HttpServer
Нашел проект по sun.HttpServer https://github.com/imetaxas/score-board-httpserver-corejava. Там...

Serialization of ArrayLiat
Всем доброго времени суток. Проблема у меня следующего характера: нужно сохранить объект...

Вопрос по Serialization
У меня наверное довольно простой вопрос, но ответа на него я не знаю :) Мне нужно создать...

DataGridView Serialization
Вообщем вопрос простой как сериализовать DataGridView - выдает ошибку - я так полагаю что для...

0
12.12.2019, 14:44
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
12.12.2019, 14:44
Помогаю со студенческими работами здесь

XML Serialization
Есть три класса, данные к-рых нужно выгрузить в хмл файл. Для этого был создан класс, в котором...

boost::serialization
Хотел бы узнать, есть ли преимущество в записи файла с boost::serialization перед обычной записью?

boost::serialization
Нечто вроде ДБ написано с использованием boost::any (любой конечный элемент ДБ, то есть содержимое...

boost::serialization
Рассматривал тему boost::serialization. И в примере ниже моя студия выкидывает много ошибок....

DataGrid, Serialization
Доброго времени суток, уважаемые форумчане. Задался таким вопросом. Полгода назад трудился над...

Xaml Serialization
Всем привет. Столкнулся с необходимостью использования xaml сериализации, может кто-нибудь...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru