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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
|
#region License
// /*
// Microsoft Public License (Ms-PL)
// MonoGame - Copyright © 2009 The MonoGame Team
//
// All rights reserved.
//
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
// accept the license, do not use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
// U.S. copyright law.
//
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
// your patent license from such contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
// notices that are present in the software.
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
// code form, you may only do so under a license that complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
// purpose and non-infringement.
// */
#endregion License
#region Using clause
using System;
using System.Collections;
using System.Collections.Generic;
#if !WINDOWS_PHONE
using System.Runtime.Remoting.Messaging;
#endif
using System.Threading;
using Microsoft.Xna.Framework.GamerServices;
#endregion Using clause
namespace Microsoft.Xna.Framework.Net
{
// The delegate must have the same signature as the method
// it will call asynchronously.
public delegate NetworkSession NetworkSessionAsynchronousCreate (
NetworkSessionType sessionType,// Type of session being hosted.
int maxLocalGamers,// Maximum number of local players on the same gaming machine in this network session.
int maxGamers, // Maximum number of players allowed in this network session. For Zune-based games, this value must be between 2 and 8; 8 is the maximum number of players supported in the session.
int privateGamerSlots, // Number of reserved private session slots created for the session. This value must be less than maximumGamers.
NetworkSessionProperties sessionProperties, // Properties of the session being created.
int hostGamer, // Gamer Index of the host
bool isHost // If the session is for host or not
);
public delegate AvailableNetworkSessionCollection NetworkSessionAsynchronousFind (
NetworkSessionType sessionType,
int hostGamer,
int maxLocalGamers,
NetworkSessionProperties searchProperties);
public delegate NetworkSession NetworkSessionAsynchronousJoin (AvailableNetworkSession availableSession);
public delegate NetworkSession NetworkSessionAsynchronousJoinInvited (int maxLocalGamers);
public sealed class NetworkSession : IDisposable
{
internal static List<NetworkSession> activeSessions = new List<NetworkSession>();
private NetworkSessionState sessionState;
//private static NetworkSessionType networkSessionType;
private GamerCollection<NetworkGamer> _allGamers;
private GamerCollection<LocalNetworkGamer> _localGamers;
private GamerCollection<NetworkGamer> _remoteGamers;
private GamerCollection<NetworkGamer> _previousGamers;
internal Queue<CommandEvent> commandQueue;
// use the static Create or BeginCreate methods
private NetworkSession ()
{
activeSessions.Add(this);
}
private NetworkSessionType sessionType;
private int maxGamers;
private int privateGamerSlots;
private NetworkSessionProperties sessionProperties;
private bool isHost = false;
private int hostGamerIndex = -1;
private NetworkGamer hostingGamer;
internal MonoGamerPeer networkPeer;
private NetworkSession (NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool isHost, int hostGamer)
: this(sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer, null)
{
}
private NetworkSession (NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, NetworkSessionProperties sessionProperties, bool isHost, int hostGamer, AvailableNetworkSession availableSession) : this()
{
if (sessionProperties == null) {
throw new ArgumentNullException ("sessionProperties");
}
_allGamers = new GamerCollection<NetworkGamer>();
_localGamers = new GamerCollection<LocalNetworkGamer>();
// for (int x = 0; x < Gamer.SignedInGamers.Count; x++) {
// GamerStates states = GamerStates.Local;
// if (x == 0)
// states |= GamerStates.Host;
// LocalNetworkGamer localGamer = new LocalNetworkGamer(this, (byte)x, states);
// localGamer.SignedInGamer = Gamer.SignedInGamers[x];
// _allGamers.AddGamer(localGamer);
// _localGamers.AddGamer(localGamer);
//
// // We will attach a property change handler to local gamers
// // se that we can broadcast the change to other peers.
// localGamer.PropertyChanged += HandleGamerPropertyChanged;
//
// }
_remoteGamers = new GamerCollection<NetworkGamer>();
_previousGamers = new GamerCollection<NetworkGamer>();
hostingGamer = null;
commandQueue = new Queue<CommandEvent>();
this.sessionType = sessionType;
this.maxGamers = maxGamers;
this.privateGamerSlots = privateGamerSlots;
this.sessionProperties = sessionProperties;
this.isHost = isHost;
this.hostGamerIndex = hostGamer;
if (isHost)
networkPeer = new MonoGamerPeer(this, null);
else
{
if (networkPeer == null)
networkPeer = new MonoGamerPeer(this, availableSession);
}
CommandGamerJoined gj = new CommandGamerJoined(hostGamer, this.isHost, true);
commandQueue.Enqueue(new CommandEvent(gj));
}
public static NetworkSession Create (
NetworkSessionType sessionType,// Type of session being hosted.
IEnumerable<SignedInGamer> localGamers, // Maximum number of local players on the same gaming machine in this network session.
int maxGamers, // Maximum number of players allowed in this network session. For Zune-based games, this value must be between 2 and 8; 8 is the maximum number of players supported in the session.
int privateGamerSlots, // Number of reserved private session slots created for the session. This value must be less than maximumGamers.
NetworkSessionProperties sessionProperties // Properties of the session being created.
)
{
try {
return EndCreate(BeginCreate(sessionType, localGamers, maxGamers,privateGamerSlots, sessionProperties,null, null));
} finally {
}
}
public static NetworkSession Create (
NetworkSessionType sessionType, // Type of session being hosted.
int maxLocalGamers, // Maximum number of local players on the same gaming machine in this network session.
int maxGamers // Maximum number of players allowed in this network session. For Zune-based games, this value must be between 2 and 8; 8 is the maximum number of players supported in the session.
)
{
try {
#if WINDOWS_PHONE
return Create(sessionType, maxLocalGamers, maxGamers, 0, null, 0, false);
#else
return EndCreate(BeginCreate(sessionType,maxLocalGamers,maxGamers,null, null));
#endif
} finally {
}
}
public static NetworkSession Create (
NetworkSessionType sessionType,
int maxLocalGamers,
int maxGamers,
int privateGamerSlots,
NetworkSessionProperties sessionProperties)
{
try {
#if WINDOWS_PHONE
return Create(sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, 0, false);
#else
return EndCreate(BeginCreate(sessionType,maxLocalGamers,maxGamers,privateGamerSlots,sessionProperties,null, null));
#endif
} finally {
}
}
private static NetworkSession Create (
NetworkSessionType sessionType,
int maxLocalGamers,
int maxGamers,
int privateGamerSlots,
NetworkSessionProperties sessionProperties,
int hostGamer,
bool isHost)
{
NetworkSession session = null;
try {
if (sessionProperties == null)
sessionProperties = new NetworkSessionProperties();
session = new NetworkSession (sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer);
} finally {
}
return session;
}
#region IDisposable Members
public void Dispose ()
{
this.Dispose(true);
GC.SuppressFinalize (this);
}
public void Dispose (bool disposing)
{
#if DEBUG
Console.WriteLine("Network Session Disposing");
#endif
if (disposing) {
foreach (Gamer gamer in _allGamers) {
gamer.Dispose();
}
//Console.WriteLine("disposing");
// Make sure we shut down our server instance as we no longer need it.
if (networkPeer != null) {
networkPeer.ShutDown();
}
if (networkPeer != null) {
networkPeer.ShutDown();
}
this._isDisposed = true;
}
}
#endregion
public void AddLocalGamer (SignedInGamer gamer)
{
if (gamer == null)
throw new ArgumentNullException ("gamer");
// _allGamers.AddGamer(gamer);
// _localGamers.AddGamer((LocalNetworkGamer)gamer);
//
// // We will attach a property change handler to local gamers
// // se that we can broadcast the change to other peers.
// gamer.PropertyChanged += HandleGamerPropertyChanged;
}
public static IAsyncResult BeginCreate (NetworkSessionType sessionType,
IEnumerable<SignedInGamer> localGamers,
int maxGamers,
int privateGamerSlots,
NetworkSessionProperties sessionProperties,
AsyncCallback callback,
Object asyncState)
{
int hostGamer = -1;
hostGamer = GetHostingGamerIndex (localGamers);
return BeginCreate (sessionType, hostGamer, 4, maxGamers, privateGamerSlots, sessionProperties, callback, asyncState);
}
public static IAsyncResult BeginCreate (
NetworkSessionType sessionType,
int maxLocalGamers,
int maxGamers,
AsyncCallback callback,
Object asyncState)
{
return BeginCreate (sessionType, -1, maxLocalGamers, maxGamers, 0, null, callback, asyncState);
}
public static IAsyncResult BeginCreate (
NetworkSessionType sessionType,
int maxLocalGamers,
int maxGamers,
int privateGamerSlots,
NetworkSessionProperties sessionProperties,
AsyncCallback callback,
Object asyncState)
{
return BeginCreate (sessionType, -1, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, callback, asyncState);
}
private static IAsyncResult BeginCreate (NetworkSessionType sessionType,
int hostGamer,
int maxLocalGamers,
int maxGamers,
int privateGamerSlots,
NetworkSessionProperties sessionProperties,
AsyncCallback callback,
Object asyncState)
{
if (maxLocalGamers < 1 || maxLocalGamers > 4)
throw new ArgumentOutOfRangeException ( "Maximum local players must be between 1 and 4." );
if (maxGamers < 2 || maxGamers > 32)
throw new ArgumentOutOfRangeException ( "Maximum number of gamers must be between 2 and 32." );
try {
NetworkSessionAsynchronousCreate AsynchronousCreate = new NetworkSessionAsynchronousCreate (Create);
return AsynchronousCreate.BeginInvoke (sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties, hostGamer, true, callback, asyncState);
} finally {
}
}
internal static int GetHostingGamerIndex (IEnumerable<SignedInGamer> localGamers)
{
SignedInGamer hostGamer = null;
if (localGamers == null) {
throw new ArgumentNullException ("localGamers");
}
foreach (SignedInGamer gamer in localGamers) {
if (gamer == null) {
throw new ArgumentException ("gamer can not be null in list of localGamers.");
}
if (gamer.IsDisposed) {
throw new ObjectDisposedException ("localGamers", "A gamer is disposed in the list of localGamers");
}
if (hostGamer == null) {
hostGamer = gamer;
}
}
if (hostGamer == null) {
throw new ArgumentException ("Invalid gamer in localGamers.");
}
return (int)hostGamer.PlayerIndex;
}
public static IAsyncResult BeginFind (
NetworkSessionType sessionType,
IEnumerable<SignedInGamer> localGamers,
NetworkSessionProperties searchProperties,
AsyncCallback callback,
Object asyncState)
{
int hostGamer = -1;
hostGamer = GetHostingGamerIndex (localGamers);
return BeginFind (sessionType, hostGamer, 4, searchProperties, callback, asyncState);
}
public static IAsyncResult BeginFind (
NetworkSessionType sessionType,
int maxLocalGamers,
NetworkSessionProperties searchProperties,
AsyncCallback callback,
Object asyncState)
{
return BeginFind (sessionType, -1, 4, searchProperties, callback, asyncState);
}
private static IAsyncResult BeginFind (
NetworkSessionType sessionType,
int hostGamer,
int maxLocalGamers,
NetworkSessionProperties searchProperties,
AsyncCallback callback,
Object asyncState)
{
if (sessionType == NetworkSessionType.Local)
throw new ArgumentException ( "NetworkSessionType cannot be NetworkSessionType.Local" );
if (maxLocalGamers < 1 || maxLocalGamers > 4)
throw new ArgumentOutOfRangeException ( "maxLocalGamers must be between 1 and 4." );
try {
NetworkSessionAsynchronousFind AsynchronousFind = new NetworkSessionAsynchronousFind (Find);
return AsynchronousFind.BeginInvoke (sessionType, hostGamer, maxLocalGamers, searchProperties, callback, asyncState);
} finally {
}
}
public static IAsyncResult BeginJoin (
AvailableNetworkSession availableSession,
AsyncCallback callback,
Object asyncState)
{
if (availableSession == null)
throw new ArgumentNullException ();
try {
NetworkSessionAsynchronousJoin AsynchronousJoin = new NetworkSessionAsynchronousJoin (JoinSession);
return AsynchronousJoin.BeginInvoke (availableSession, callback, asyncState);
} finally {
}
}
public static IAsyncResult BeginJoinInvited (
IEnumerable<SignedInGamer> localGamers,
AsyncCallback callback,
Object asyncState)
{
try {
throw new NotImplementedException ();
} finally {
}
}
public static IAsyncResult BeginJoinInvited (
int maxLocalGamers,
AsyncCallback callback,
Object asyncState)
{
if (maxLocalGamers < 1 || maxLocalGamers > 4)
throw new ArgumentOutOfRangeException ( "maxLocalGamers must be between 1 and 4." );
try {
NetworkSessionAsynchronousJoinInvited AsynchronousJoinInvited = new NetworkSessionAsynchronousJoinInvited (JoinInvited);
return AsynchronousJoinInvited.BeginInvoke (maxLocalGamers, callback, asyncState);
} finally {
}
}
public static NetworkSession EndCreate (IAsyncResult result)
{
NetworkSession returnValue = null;
try {
#if WINDOWS_PHONE
return null;
#else
// Retrieve the delegate.
AsyncResult asyncResult = (AsyncResult)result;
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne ();
// Call EndInvoke to retrieve the results.
if (asyncResult.AsyncDelegate is NetworkSessionAsynchronousCreate) {
returnValue = ((NetworkSessionAsynchronousCreate)asyncResult.AsyncDelegate).EndInvoke (result);
}
#endif
} finally {
// Close the wait handle.
result.AsyncWaitHandle.Close ();
}
return returnValue;
}
public static AvailableNetworkSessionCollection EndFind (IAsyncResult result)
{
AvailableNetworkSessionCollection returnValue = null;
List<AvailableNetworkSession> networkSessions = new List<AvailableNetworkSession>();
try {
// Retrieve the delegate.
#if WINDOWS_PHONE
MonoGamerPeer.FindResults(networkSessions);
#else
AsyncResult asyncResult = (AsyncResult)result;
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne ();
// Call EndInvoke to retrieve the results.
if (asyncResult.AsyncDelegate is NetworkSessionAsynchronousFind) {
returnValue = ((NetworkSessionAsynchronousFind)asyncResult.AsyncDelegate).EndInvoke (result);
MonoGamerPeer.FindResults(networkSessions);
}
#endif
} finally {
// Close the wait handle.
result.AsyncWaitHandle.Close ();
}
returnValue = new AvailableNetworkSessionCollection(networkSessions);
return returnValue;
}
public void EndGame ()
{
try {
CommandSessionStateChange ssc = new CommandSessionStateChange(NetworkSessionState.Lobby, sessionState);
commandQueue.Enqueue(new CommandEvent(ssc));
} finally {
}
}
public static NetworkSession EndJoin (IAsyncResult result)
{
NetworkSession returnValue = null;
try {
#if WINDOWS_PHONE
#else
// Retrieve the delegate.
AsyncResult asyncResult = (AsyncResult)result;
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne ();
// Call EndInvoke to retrieve the results.
if (asyncResult.AsyncDelegate is NetworkSessionAsynchronousJoin) {
returnValue = ((NetworkSessionAsynchronousJoin)asyncResult.AsyncDelegate).EndInvoke (result);
}
#endif
} finally {
// Close the wait handle.
result.AsyncWaitHandle.Close ();
}
return returnValue;
}
public static NetworkSession EndJoinInvited (IAsyncResult result)
{
NetworkSession returnValue = null;
try {
#if WINDOWS_PHONE
#else
// Retrieve the delegate.
AsyncResult asyncResult = (AsyncResult)result;
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne ();
// Call EndInvoke to retrieve the results.
if (asyncResult.AsyncDelegate is NetworkSessionAsynchronousJoinInvited) {
returnValue = ((NetworkSessionAsynchronousJoinInvited)asyncResult.AsyncDelegate).EndInvoke (result);
}
#endif
} finally {
// Close the wait handle.
result.AsyncWaitHandle.Close ();
}
return returnValue;
}
public static AvailableNetworkSessionCollection Find (
NetworkSessionType sessionType,
IEnumerable<SignedInGamer> localGamers,
NetworkSessionProperties searchProperties)
{
int hostGamer = -1;
hostGamer = GetHostingGamerIndex(localGamers);
#if WINDOWS_PHONE
return Find(sessionType, hostGamer, 4, null);
#else
return EndFind(BeginFind(sessionType, hostGamer, 4, searchProperties,null,null));
#endif
}
public static AvailableNetworkSessionCollection Find (
NetworkSessionType sessionType,
int maxLocalGamers,
NetworkSessionProperties searchProperties)
{
return EndFind(BeginFind(sessionType, -1, maxLocalGamers, searchProperties,null,null));
}
private static AvailableNetworkSessionCollection Find (
NetworkSessionType sessionType,
int hostGamer,
int maxLocalGamers,
NetworkSessionProperties searchProperties)
{
try {
if (maxLocalGamers < 1 || maxLocalGamers > 4)
throw new ArgumentOutOfRangeException ( "maxLocalGamers must be between 1 and 4." );
List<AvailableNetworkSession> availableNetworkSessions = new List<AvailableNetworkSession> ();
MonoGamerPeer.Find(sessionType);
return new AvailableNetworkSessionCollection ( availableNetworkSessions );
} finally {
}
}
public NetworkGamer FindGamerById (byte gamerId)
{
try {
foreach (NetworkGamer gamer in _allGamers) {
if (gamer.Id == gamerId)
return gamer;
}
return null;
} finally {
}
}
public static NetworkSession Join (AvailableNetworkSession availableSession)
{
#if WINDOWS_PHONE
return JoinSession(availableSession);
#else
return EndJoin(BeginJoin(availableSession, null, null));
#endif
}
private static NetworkSession JoinSession (AvailableNetworkSession availableSession)
{
NetworkSession session = null;
try {
NetworkSessionType sessionType = availableSession.SessionType;
int maxGamers = 32;
int privateGamerSlots = 0;
bool isHost = false;
int hostGamer = -1;
NetworkSessionProperties sessionProperties = availableSession.SessionProperties;
if (sessionProperties == null)
sessionProperties = new NetworkSessionProperties();
session = new NetworkSession (sessionType, maxGamers, privateGamerSlots, sessionProperties, isHost, hostGamer, availableSession);
} finally {
}
return session;
}
public static NetworkSession JoinInvited (IEnumerable<SignedInGamer> localGamers)
{
try {
throw new NotImplementedException ();
} finally {
}
}
public static NetworkSession JoinInvited (int maxLocalGamers)
{
if (maxLocalGamers < 1 || maxLocalGamers > 4)
throw new ArgumentOutOfRangeException ( "maxLocalGamers must be between 1 and 4." );
try {
throw new NotImplementedException ();
} finally {
}
}
// I am not really sure how this is suppose to work so am just fleshing it in
// for the way I think it should. This will also send a message to all connected
// peers for a state change.
public void ResetReady ()
{
foreach (NetworkGamer gamer in _localGamers) {
gamer.IsReady = false;
}
}
public void StartGame ()
{
try {
CommandSessionStateChange ssc = new CommandSessionStateChange(NetworkSessionState.Playing, sessionState);
commandQueue.Enqueue(new CommandEvent(ssc));
//sessionState = NetworkSessionState.Playing;
} finally {
}
}
public void Update ()
{
// Updates the state of the multiplayer session.
try {
while (commandQueue.Count > 0 && networkPeer.IsReady) {
var command = (CommandEvent)commandQueue.Dequeue();
// for some screwed up reason we are dequeueing something
// that is null so we will just continue. I am not sure
// if is jumbled data coming in from the connection or
// something that is not being done correctly in code
// For sure this needs to be looked at although it is not
// causing any real problems right now.
if (command == null) {
continue;
}
switch (command.Command) {
case CommandEventType.SendData:
ProcessSendData((CommandSendData)command.CommandObject);
break;
case CommandEventType.ReceiveData:
ProcessReceiveData((CommandReceiveData)command.CommandObject);
break;
case CommandEventType.GamerJoined:
ProcessGamerJoined((CommandGamerJoined)command.CommandObject);
break;
case CommandEventType.GamerLeft:
ProcessGamerLeft((CommandGamerLeft)command.CommandObject);
break;
case CommandEventType.SessionStateChange:
ProcessSessionStateChange((CommandSessionStateChange)command.CommandObject);
break;
case CommandEventType.GamerStateChange:
ProcessGamerStateChange((CommandGamerStateChange)command.CommandObject);
break;
}
}
}
catch (Exception exc) {
#if DEBUG
Console.WriteLine("Error in NetworkSession Update: " + exc.Message);
#endif
}
finally {
}
}
private void ProcessGamerStateChange(CommandGamerStateChange command)
{
networkPeer.SendGamerStateChange(command.Gamer);
}
private void ProcessSendData(CommandSendData command)
{
networkPeer.SendData(command.data, command.options);
NetworkGamer sender;
CommandReceiveData crd = new CommandReceiveData (command.sender.RemoteUniqueIdentifier,
command.data);
crd.gamer = command.sender;
foreach(LocalNetworkGamer gamer in _localGamers) {
gamer.receivedData.Enqueue(crd);
}
}
private void ProcessReceiveData(CommandReceiveData command)
{
// first let's look up the gamer that sent the data
foreach (NetworkGamer gamer in _allGamers) {
if (gamer.RemoteUniqueIdentifier == command.remoteUniqueIdentifier)
command.gamer = gamer;
}
// for some reason this is null sometimes
// this needs to be looked into instead of the
// check below
if (command.gamer == null)
return;
// now we loop through each of our local gamers and add the command
// to be processed.
foreach (LocalNetworkGamer localGamer in LocalGamers) {
lock (localGamer.receivedData) {
localGamer.receivedData.Enqueue(command);
}
}
}
private void ProcessSessionStateChange(CommandSessionStateChange command)
{
if (sessionState == command.NewState)
return;
sessionState = command.NewState;
switch (command.NewState) {
case NetworkSessionState.Ended:
ResetReady();
if (SessionEnded != null) {
// Have to find an example of how this is used so that I can figure out how to pass
// the EndReason
SessionEnded(this, new NetworkSessionEndedEventArgs(NetworkSessionEndReason.HostEndedSession));
}
break;
case NetworkSessionState.Playing:
if (GameStarted != null) {
GameStarted(this, new GameStartedEventArgs());
}
break;
}
// if changing from playing to lobby
if (command.NewState == NetworkSessionState.Lobby && command.OldState == NetworkSessionState.Playing) {
ResetReady();
if (GameEnded != null) {
GameEnded(this, new GameEndedEventArgs());
}
}
}
private void ProcessGamerJoined(CommandGamerJoined command)
{
NetworkGamer gamer;
if ((command.State & GamerStates.Local) != 0) {
gamer = new LocalNetworkGamer(this, (byte)command.InternalIndex, command.State);
_allGamers.AddGamer(gamer);
_localGamers.AddGamer((LocalNetworkGamer)gamer);
// Note - This might be in the wrong place for certain connections
// Take a look at HoneycombRush tut for debugging later.
if (Gamer.SignedInGamers.Count >= _localGamers.Count)
((LocalNetworkGamer)gamer).SignedInGamer = Gamer.SignedInGamers[_localGamers.Count - 1];
// We will attach a property change handler to local gamers
// se that we can broadcast the change to other peers.
gamer.PropertyChanged += HandleGamerPropertyChanged;
}
else {
gamer = new NetworkGamer (this, (byte)command.InternalIndex, command.State);
gamer.DisplayName = command.DisplayName;
gamer.Gamertag = command.GamerTag;
gamer.RemoteUniqueIdentifier = command.remoteUniqueIdentifier;
_allGamers.AddGamer(gamer);
_remoteGamers.AddGamer(gamer);
}
if ((command.State & GamerStates.Host) != 0)
hostingGamer = gamer;
gamer.Machine = new NetworkMachine();
gamer.Machine.Gamers.AddGamer(gamer);
//gamer.IsReady = true;
if (GamerJoined != null) {
GamerJoined(this, new GamerJoinedEventArgs(gamer));
}
if (networkPeer != null && (command.State & GamerStates.Local) == 0) {
networkPeer.SendPeerIntroductions(gamer);
}
if (networkPeer != null)
{
networkPeer.UpdateLiveSession(this);
}
}
private void ProcessGamerLeft(CommandGamerLeft command)
{
NetworkGamer gamer;
for (int x = 0; x < _remoteGamers.Count; x++) {
if (_remoteGamers[x].RemoteUniqueIdentifier == command.remoteUniqueIdentifier) {
gamer = _remoteGamers[x];
_remoteGamers.RemoveGamer(gamer);
_allGamers.RemoveGamer(gamer);
if (GamerLeft != null) {
GamerLeft(this, new GamerLeftEventArgs(gamer));
}
}
}
if (networkPeer != null)
{
networkPeer.UpdateLiveSession(this);
}
}
void HandleGamerPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
NetworkGamer gamer = sender as NetworkGamer;
if (gamer == null)
return;
// If the gamer is local then we need to broadcast that change to all other
// connected peers. This is a double check here as we should only be handling
// property changes for local gamers for now.
if (gamer.IsLocal) {
CommandGamerStateChange sc = new CommandGamerStateChange(gamer);
CommandEvent cmd = new CommandEvent(sc);
commandQueue.Enqueue(cmd);
}
}
#region Properties
public GamerCollection<NetworkGamer> AllGamers {
get {
return _allGamers;
}
}
bool _AllowHostMigration = false;
public bool AllowHostMigration {
get {
return _AllowHostMigration;
}
set {
if (_AllowHostMigration != value) {
_AllowHostMigration = value;
}
}
}
bool _AllowJoinInProgress = false;
public bool AllowJoinInProgress {
get {
return _AllowJoinInProgress;
}
set {
if (_AllowJoinInProgress != value) {
_AllowJoinInProgress = value;
}
}
}
public int BytesPerSecondReceived {
get {
throw new NotImplementedException ();
}
}
public int BytesPerSecondSent {
get {
throw new NotImplementedException ();
}
}
public NetworkGamer Host {
get {
return hostingGamer;
}
}
bool _isDisposed = false;
public bool IsDisposed {
get {
return _isDisposed; // TODO (this.kernelHandle == 0);
}
}
public bool IsEveryoneReady {
get {
if (_allGamers.Count == 0)
return false;
foreach (NetworkGamer gamer in _allGamers) {
if (!gamer.IsReady) {
return false;
}
}
return true;
}
}
public bool IsHost {
get {
return isHost;
}
}
public GamerCollection<LocalNetworkGamer> LocalGamers {
get {
return _localGamers;
}
}
public int MaxGamers {
get {
return maxGamers;
}
set {
maxGamers = value;
}
}
public GamerCollection<NetworkGamer> PreviousGamers {
get {
return _previousGamers;
}
}
public int PrivateGamerSlots {
get {
return privateGamerSlots;
}
set {
privateGamerSlots = value;
}
}
public GamerCollection<NetworkGamer> RemoteGamers {
get {
return _remoteGamers;
}
}
public NetworkSessionProperties SessionProperties {
get {
return sessionProperties;
}
}
public NetworkSessionState SessionState {
get {
return sessionState;
}
}
public NetworkSessionType SessionType {
get {
return sessionType;
}
}
private TimeSpan defaultSimulatedLatency = new TimeSpan(0, 0, 0);
public TimeSpan SimulatedLatency {
get {
#if DEBUG
if (networkPeer != null)
{
return networkPeer.SimulatedLatency;
}
#endif
return defaultSimulatedLatency;
}
set {
defaultSimulatedLatency = value;
#if DEBUG
if (networkPeer != null)
{
networkPeer.SimulatedLatency = value;
}
#endif
}
}
private float simulatedPacketLoss = 0.0f;
public float SimulatedPacketLoss {
get {
if (networkPeer != null)
{
simulatedPacketLoss = networkPeer.SimulatedPacketLoss;
}
return simulatedPacketLoss;
}
set {
if (networkPeer != null) networkPeer.SimulatedPacketLoss = value;
simulatedPacketLoss = value;
}
}
#endregion
#region Events
public event EventHandler<GameEndedEventArgs> GameEnded;
public event EventHandler<GamerJoinedEventArgs> GamerJoined;
public event EventHandler<GamerLeftEventArgs> GamerLeft;
public event EventHandler<GameStartedEventArgs> GameStarted;
public event EventHandler<HostChangedEventArgs> HostChanged;
public static event EventHandler<InviteAcceptedEventArgs> InviteAccepted;
public event EventHandler<NetworkSessionEndedEventArgs> SessionEnded;
#endregion
internal static void Exit()
{
if (Net.NetworkSession.activeSessions != null && Net.NetworkSession.activeSessions.Count > 0)
{
foreach (Net.NetworkSession session in Net.NetworkSession.activeSessions)
{
if (!session.IsDisposed)
{
session.Dispose();
}
}
}
}
}
public class GameEndedEventArgs : EventArgs
{
}
public class GamerJoinedEventArgs : EventArgs
{
private NetworkGamer gamer;
public GamerJoinedEventArgs (NetworkGamer aGamer)
{
gamer = aGamer;
}
public NetworkGamer Gamer {
get {
return gamer;
}
}
}
public class GamerLeftEventArgs : EventArgs
{
private NetworkGamer gamer;
public GamerLeftEventArgs (NetworkGamer aGamer)
{
gamer = aGamer;
}
public NetworkGamer Gamer {
get {
return gamer;
}
}
}
public class GameStartedEventArgs : EventArgs
{
}
public class HostChangedEventArgs : EventArgs
{
private NetworkGamer newHost;
private NetworkGamer oldHost;
public HostChangedEventArgs (NetworkGamer aNewHost, NetworkGamer aOldHost)
{
newHost = aNewHost;
oldHost = aOldHost;
}
public NetworkGamer NewHost {
get {
return newHost;
}
}
public NetworkGamer OldHost {
get {
return oldHost;
}
}
}
public class InviteAcceptedEventArgs : EventArgs
{
private SignedInGamer gamer;
public InviteAcceptedEventArgs (SignedInGamer aGamer)
{
gamer = aGamer;
}
public SignedInGamer Gamer {
get {
return gamer;
}
}
public bool IsCurrentSession {
get {
return false;
}
}
}
public class NetworkSessionEndedEventArgs : EventArgs
{
NetworkSessionEndReason endReason;
public NetworkSessionEndedEventArgs (NetworkSessionEndReason aEndReason)
{
endReason = aEndReason;
}
public NetworkSessionEndReason EndReason {
get {
return endReason;
}
}
}
}
|