T
T
TheTalion2016-10-07 14:46:41
C++ / C#
TheTalion, 2016-10-07 14:46:41

Websocket: accepting a message and writing part of it to a separate variable. How to implement?

I have a server and a client. Communicate via websocket.
One of them sends such a message (it does not matter who), for example:

на C#
string CurPos = "F1";
string NewPos = "F2";
con.Send("Change position: " + CurPos + "-" + NewPos);

Но другой получает такое сообщение:
string newMsg = "Change position: F1-F2";
Как сделать, чтобы получаемые символы на определенных местах записывались в, например, заранее оглашенные переменные? Хотелось бы также увидеть пример реализации хотя бы с одной переменной, то не совсем понимаю, как это работает.
Пробовал сделать через Regex, но как я понял, он воспринимает просто строку, которая содержит совпадения по тексту, но не понял как разделить строку на подстроки, чтобы из них выделить отдельные переменные.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pi314, 2016-10-07
@TheTalion

Как сделать, чтобы получаемые символы на определенных местах записывались в, например, заранее оглашенные переменные?

To do this, you need to parse the string, select the substrings of interest and put them into the necessary variables yourself. There is no magic that will do it for you. In this sense, it makes no difference where the string came from: from the websocket, from the console, or from somewhere else :)
You can do this with regular expressions, loops, or any other intricate way, but before doing this, you need to understand exactly what to do. And here are the options.
1. The line is exactly as described in the question, and there is no way to change it, because it is sent by a "foreign" code.
Then you need to describe the structure of the separators of the parts of interest with a regular expression (if it is regular at all) and highlight them with a regular expression, for example, like this:
string[] tokens = Regex.Split("Change position: F1-F2", @"(: )|(-)", RegexOptions.ExplicitCapture);

if( tokens.Length == 3 && string.Equals(tokens[0], "Change position") )
{
  curPos = tokens[1];
  newPos = tokens[2];
} else {
  // прислали какую-то непонятную хрень...
}

You can play around, test regular expressions on your own and see what they can parse and what not, for example, here .
2. The line can be defined independently.
Then it's better to come up with a protocol (more specifically, a string format) that would be easy to parse. For example:
event:cur-position:new-position
i.e. for this example, send:
"Change position:F1:F2"
Such a string can be parsed with an elementary
string[] tokens = "Change position:F1:F2".Split(':');

if( tokens.Length == 3 && string.Equals(tokens[0], "Change position") )
{
  curPos = tokens[1];
  newPos = tokens[2];
} else {
  // прислали какую-то непонятную хрень...
}

In both cases, you need to remember that, in principle, not only "our" client, but also any prankster in general can connect to the websocket and send something there that we do not expect at all. Accordingly, before stupidly parsing, it would be good to check the string for correctness and, at least, process possible errors during parsing (this is not in the code example given - a task for self-study).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question