private void StartReceive() { new Thread(delegate() { byte[] buffer = new byte[DATA_LENGTH]; while (true) { try { if (isClosed || !socket.Connected) { //Close(); return; } buffer = new byte[socket.Available]; int length = socket.Receive(buffer, buffer.Length, SocketFlags.None); if (length <= 0) { continue; } string packetString = Encoding.Default.GetString(buffer); OnReceive(packetString); //Thread.Sleep(1); } catch (Exception e) { Eutils.FileError(String.Format("{0} {1} \n", e.Message, e.StackTrace), "client_error.txt"); Eutils.WriteLine("Error Receiving! Message:{0} Stacktrace: {1}", Eutils.MESSSAGE_TYPE.ERROR, e.Message, e.StackTrace); Close(); break; } } }).Start(); }
private void ReceiveCallback(IAsyncResult ar) { try { StateObject state = (StateObject)ar.AsyncState; if (isClosed || socket == null || !socket.Connected || socket.Available != 0 || socket.Poll(0, SelectMode.SelectRead)) { Close(); return; } // Read data from the client socket. int bytesRead = socket.EndReceive(ar); //More data if (bytesRead > 0) { state.stringBuilder.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); string packetData = state.stringBuilder.ToString(); state = new StateObject();//reset socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); OnReceive(packetData); } } catch (Exception e) { Eutils.FileError(String.Format("{0} {1} \n", e.Message, e.StackTrace), "client_error.txt"); Eutils.WriteLine("Error receiving:{0} {1}", Eutils.MESSSAGE_TYPE.ERROR, e.Message, e.StackTrace); Close(); } }
public void Send(string dataToSend) { if (isClosed) { return; } if (socket == null || !socket.Connected) { Close(); return; } dataToSend = QEncryption.Encrypt(dataToSend); dataToSend = PacketDatas.PACKET_HEADER + dataToSend; //We us UTF8 characterss so lets convert the bytes into utf8 string! byte[] dataBytes = Encoding.UTF8.GetBytes(dataToSend); //And then send it to our client. try { socket.Send(dataBytes, SocketFlags.None); } catch (Exception e) { Eutils.FileError(String.Format("{0} {1} \n", e.Message, e.StackTrace), "client_error.txt"); Eutils.WriteLine("Error Sending! Message:{0}", Eutils.MESSSAGE_TYPE.ERROR, e.Message, e.StackTrace); Close(); } }
private void OnReceive(string packetString) { //Then we send this. if (packetString[0].ToString() != PacketDatas.PACKET_HEADER) { Close(); return; } string[] packets = packetString.Split(new string[] { PacketDatas.PACKET_HEADER }, StringSplitOptions.None); for (int i = 1; i < packets.Length; i++) { //Eutils.WriteLine("received data:{0} at Time:{1} Length:{2}", Eutils.MESSSAGE_TYPE.NORMAL, packets[i], DateTime.Now, packets[i].Length); packets[i] = QEncryption.Decrypt(packets[i]); Eutils.WriteLine("decrypted data:{0} at Time:{1} Length:{2}", Eutils.MESSSAGE_TYPE.NORMAL, packets[i], DateTime.Now, packets[i].Length); if (packets[i] == "NULL") { Eutils.FileError(String.Format("{0} \n", "Error decrypting: packets[i] == NULL"), "client_error.txt"); Eutils.WriteLine("Error decrypting", Eutils.MESSSAGE_TYPE.ERROR); //Close(); break; } //Split the packet by our split character. string[] packetStrings = packets[i].Split(new string[] { PacketDatas.PACKET_SPLIT }, StringSplitOptions.None); received(this, packetStrings); } }
protected override void client_received(Client sender, string[] packetStrings) { switch (packetStrings[0]) { case PacketDatas.PACKET_CHAT: DoChat(sender, packetStrings); break; case PacketDatas.PACKET_GAME_CREATE: CreateGameRoom(sender, packetStrings); break; case PacketDatas.PACKET_GAME_SEL: SelectGameRoom(sender, packetStrings); break; case PacketDatas.PACKET_GET_GAME_ROOM: GameRoomsUpdate(sender, packetStrings); break; default: Eutils.WriteLine("Lobby Error wrong packet! {0}", Eutils.MESSSAGE_TYPE.WARNING, packetStrings[1]); break; } }
protected override void client_received(Client sender, string[] packetStrings) { switch (packetStrings[0]) { case PacketDatas.PACKET_CHAT: DoChat(sender, packetStrings); break; case PacketDatas.PACKET_GAME_STOP: GameStop(sender, packetStrings); break; case PacketDatas.PACKET_GAME_POS: DoSendPos(sender, packetStrings); break; case PacketDatas.PACKET_GAME_IMAGE_START: DoSendImageStart(sender, packetStrings); break; case PacketDatas.PACKET_GAME_IMAGE: DoSendImage(sender, packetStrings); break; case PacketDatas.PACKET_GAME_IMAGE_END: DoSendImageEnd(sender, packetStrings); break; default: Eutils.WriteLine("[Gameroom InGame {1}] Error wrong packet! {0}", Eutils.MESSSAGE_TYPE.ERROR, packetStrings[1], gameRoom.gameRoomName); break; } }
public GameRoom(Client owner, Lobby lLobby, string name = "null") : base() { lobby = lLobby; gameroomOwner = owner; gameRoomName = name; Eutils.WriteLine("Created Gameroom {0}", Eutils.MESSSAGE_TYPE.NORMAL, name); }
//The login function. private void DoLogin(Client sender, String[] packetStrings) { bool userCorrect = true; //Correct bool passCorrect = true; //correct //Everything needs to be right. If something is wrong then goodbye. if (!userCorrect || !passCorrect || packetStrings[1].Length < 1 || packetStrings[2].Length < 1) { //<3 the first packed you see! //We send a error packet. sender.Send(PacketDatas.PACKET_ERROR + PacketDatas.PACKET_SPLIT + "Invalid username or password"); Eutils.WriteLine("Login in failed by ip: {0}", Eutils.MESSSAGE_TYPE.WARNING, sender.ipEndpoint.Address); sender.Close();//DC return; } //Set the username sender.userName = packetStrings[1]; sender.isLoggedIn = true; //Login succes! We just send a login packet back sender.Send(PacketDatas.PACKET_LOGIN); Eutils.WriteLine("Login in:{0} with password:{1} ip: {2}", Eutils.MESSSAGE_TYPE.NORMAL, packetStrings[1], packetStrings[2], sender.ipEndpoint.Address); //We remove the receive event to so the lobby can handle the receiving now. RemoveClient(sender); //Add client to the lobby. lobby.AddClient(sender); }
protected override void visitor_disconnected(Client sender) { disCount++; base.visitor_disconnected(sender); Eutils.WriteLine("Client Disconnected: {0}", Eutils.MESSSAGE_TYPE.NORMAL, sender.ID); UpdateStats(); Sweep(); }
//The big received function. protected override void client_received(Client sender, string[] packetStrings) { //So what kind of packet is it? switch (packetStrings[0]) { default: Eutils.WriteLine("main server Error wrong packet! {0}", Eutils.MESSSAGE_TYPE.WARNING); break; } }
protected override void client_received(Client sender, string[] packetStrings) { //So what kind of packet is it? switch (packetStrings[0]) { case PacketDatas.PACKET_LOGIN: //Login packet! we log in. DoLogin(sender, packetStrings); //Do this function. break; default: Eutils.WriteLine("Login Error wrong packet! {0}", Eutils.MESSSAGE_TYPE.WARNING, packetStrings[1]); break; } }
protected override void client_received(Client sender, string[] packetStrings) { switch (packetStrings[0]) { case PacketDatas.PACKET_CHAT: DoChat(sender, packetStrings); break; case PacketDatas.PACKET_GAME_START: DoStartGame(sender, packetStrings); break; default: Eutils.WriteLine("[Gameroom {1}] Error wrong packet! {0}", Eutils.MESSSAGE_TYPE.WARNING, packetStrings[1], gameRoomName); break; } }
//A client got connected! Aka socket accepted! private void listener_SocketAccepted(Socket e) { Client client = new Client(e); //it is a client. Eutils.WriteLine("Client Connected: {0}", Eutils.MESSSAGE_TYPE.NORMAL, client.ID); //Client.ID is random, every client is unique AddClient(client); if (clients.Count <= maxCount) { login.AddClient(client); client.received -= new Client.ClientReceivedHandler(client_received); UpdateStats(); } else { client.Close(); } }
public void Start() { //Are we already listening? if (bListening) { return;//then we shouldn't listen again } //Lets bind! we are going to bind on a port! sSocket.Bind(new IPEndPoint(0, nPort)); //Now we are going to listen. sSocket.Listen(0); //asynchronous accepting clients. // StartListening(); sSocket.BeginAccept(beginAcceptCallback, null); bListening = true;//We are ready and listening. Eutils.WriteLine("Server is Listening on port {0}", Eutils.MESSSAGE_TYPE.NORMAL, nPort); }
private void Sweep() { for (int i = 0; i < clients.Count; i++) { if (clients[i] == null) { clients.RemoveAt(i); i--; } else if (clients[i].isClosed) { clients.RemoveAt(i); i--; } } Eutils.WriteLine("Clients Sweeped", Eutils.MESSSAGE_TYPE.NORMAL); UpdateStats(); }
//when a client got accepted this happends. void beginAcceptCallback(IAsyncResult ar) { try { Socket s = sSocket.EndAccept(ar); //Lets get the clients socket! if (socketAccepted != null) //if no one is listening then we can't send it. { //Lets send this event with the clients socket socketAccepted(s); } //And we start over again. //A loop! sSocket.BeginAccept(beginAcceptCallback, null); } catch (Exception e) { Eutils.WriteLine("Error accepting! Message:{0}", Eutils.MESSSAGE_TYPE.ERROR, e.Message, e.StackTrace); } }
private void StartListening() { new Thread(delegate() { while (true) { try { Socket socket = sSocket.Accept(); socket.NoDelay = true; socketAccepted(socket); } catch (Exception e) { Eutils.WriteLine("Error Accepting! Message:{0}", Eutils.MESSSAGE_TYPE.ERROR, e.Message, e.StackTrace); continue; } } }).Start(); }