void HandleAcceptedConnection(TcpClient client, SharpClient sclient) { SharpSerializer syncPack = SharpSerializer.Create(); syncPack.Write((byte)IncomingConnectionResponse.Approved); short netID = this.room.NextFreeID; sclient.AssingNetID(netID); syncPack.Write(netID); this.room.Write(ref syncPack); TCPMessageHandler.Write(client, syncPack.DataAndPost()); this.room.AssignClient(sclient); Thread t = new Thread(() => ListenClient(sclient)); sclient.ListeningThread = t; sclient.Connection = client; t.Start(); S_OnClientConnected(sclient); }
public bool Connect(string IP, int Port, string Password, SharpClient Self, out ConnectResults result) { if (Password == null) { Password = ""; } if (this.connected) { result = ConnectResults.AlreadyConnected; return(false); } try { server_client = new TcpClient(); IPAddress address = null; #region IP Parse try { address = IPAddress.Parse(IP); } catch { result = ConnectResults.InvalidIpAddress; return(false); } #endregion IPEndPoint remoteAddress = new IPEndPoint(address, Port); #region Physical Connetion try { server_client.Connect(remoteAddress); } catch { result = ConnectResults.UnhandledException; return(false); } #endregion #region ID Self SharpSerializer hailMessage = SharpSerializer.Create(); hailMessage.Write((byte)IncomingConnectionRequests.ConnectionApprove); Self.Write(ref hailMessage); hailMessage.Write(Password); TCPMessageHandler.Write(server_client, hailMessage.DataAndPost()); #endregion #region Wait For Response byte[] responseRaw = TCPMessageHandler.Read(server_client); SharpSerializer response = SharpSerializer.Create(responseRaw); #endregion IncomingConnectionResponse message = (IncomingConnectionResponse)response.ReadByte(); if (message == IncomingConnectionResponse.WrongPassword) { TCPMessageHandler.CloseConnection(server_client); result = ConnectResults.InvalidPassword; return(false); } if (message == IncomingConnectionResponse.ServerIsFull) { TCPMessageHandler.CloseConnection(server_client); result = ConnectResults.ServerIsFull; return(false); } if (message == IncomingConnectionResponse.NameIsExist) { TCPMessageHandler.CloseConnection(server_client); result = ConnectResults.NameIsExist; return(false); } short myID = response.ReadInt16(); Self.AssingNetID(myID); this.room = new SharpRoom(ref response); this.listenerThread = new Thread(ListenServer); this.listenerThread.Start(); connected = true; me = Self; room.AssignClient(me); room.Server.Connection = server_client; room.Server.ListeningThread = listenerThread; C_OnConnected(room); result = ConnectResults.Succes; return(true); } catch (Exception e) { try { TCPMessageHandler.CloseConnection(server_client); } catch { } server_client = null; connected = false; try { listenerThread.Abort(); } catch { } listenerThread = null; me = null; room = null; result = ConnectResults.UnhandledException; return(false); } }