/// <summary> /// попытка соединения /// </summary> private static void ConnectCallback(IAsyncResult ar) { JoinGamePage page = null; try { StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; page = (JoinGamePage)state.obj; client.EndConnect(ar); Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()); JObject jObject = new JObject(); jObject.Add(JsonStructInfo.Type, Request.EnumTypeToString(Request.RequestTypes.GetGames)); jObject.Add(JsonStructInfo.Result, ""); string s = jObject.ToString() + JsonStructInfo.EndOfMessage; Send(state, s); } catch (Exception e) { GoToErrorPage(page); Debug.WriteLine(e.ToString()); return; } }
/// <summary> /// Получение ответа от сервера /// </summary> private static async void ReceiveCallback(IAsyncResult ar) { Frame parent = null; Page page = null; try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; JoinGamePage startPage = state.obj as JoinGamePage; page = (JoinGamePage)state.obj; await page.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { parent = page.Parent as Frame; }); // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead)); // Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } else { // All the data has arrived; put it in response. if (state.sb.Length > 1) { string resp = state.sb.ToString(); response = resp.Remove(resp.LastIndexOf(JsonStructInfo.EndOfMessage)); } client.Shutdown(SocketShutdown.Both); client.Close(); pingDone.Set(); } } catch (Exception e) { GoToErrorPage(page); Debug.WriteLine(e.ToString()); return; } }
/// <summary> /// Отправка сообщения на сервер. /// </summary> private static void Send(StateObject state, String data) { JoinGamePage page = null; try { Socket client = state.workSocket; page = (JoinGamePage)state.obj; byte[] byteData = Encoding.UTF8.GetBytes(data); client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state); } catch (Exception e) { GoToErrorPage(page); Debug.WriteLine(e.ToString()); return; } }