private void StartServer_Load(object sender, EventArgs e) { if (Owner == null || Owner.GetType() != typeof(FIR)) { throw new Exception("无效的父对象!"); } owner = (FIR)Owner; }
void receiver() { while (true) { MessageType type; int x, y; string ChatStr; byte[] getLength = new byte[4]; int alllength; try { alllength = socket.Receive(getLength, 4, SocketFlags.None); } catch (Exception e) { Console.WriteLine(e.Message); goto End; } alllength = BitConverter.ToInt32(getLength, 0); byte[] head = new byte[alllength]; byte[] temp = new byte[alllength]; Array.Copy(getLength, head, 4); try { int sub = alllength - 4; int length; while (true) { int l = (temp.Length < sub) ? temp.Length : sub; length = socket.Receive(temp, l, SocketFlags.None); if (length <= 0) { goto End; } if (length == sub) { Array.Copy(temp, 0, head, head.Length - sub, length); break; } else // if (length < sub) { Array.Copy(temp, 0, head, head.Length - sub, length); sub -= length; } } StreamHead.Read(head, out type, out x, out y, out ChatStr); if (type == MessageType.Reset) { FIR.Piece self = random.Next(0, 2) == 0 ? FIR.Piece.Black : FIR.Piece.White; FIR.Piece now = FIR.Piece.Black; // 先设置棋子 再请求刷新 否则可能不一致 Owner.RefreshText(self, now); Owner.Reset(); Send(MessageType.Piece, (int)FIR.Reserve(self), (int)now); } if (type == MessageType.Piece) { FIR.Piece self = (FIR.Piece)x; FIR.Piece now = (FIR.Piece)y; Owner.RefreshText(self, now); Owner.Reset(); } if (type == MessageType.Set) { Owner.Set(new Point(x, y), false); } if (type == MessageType.Chat) { Owner.ChatRecv(ChatStr); } } catch (Exception e) { Console.WriteLine(e.Message); goto End; } } End: new Thread(abort).Start(); }