שרת לקוח גרסה מעודכנת לתאריך 12.03.2023

קישור לקובץ

תוכן עניינים

Client 2

ClientMainWin. 2

Design. 2

Code. 2

clientLoginWin. 4

Design. 4

Code. 4

clientConnectionManager 5

Server 6

Ifs. 6

ConnectedPlayer 6

ConnectionManager 7

MessageModel 9

MessgaeHandeling. 9

PlayerS. 10

ProtocolInterface. 11

ServerMainWin. 12

Design. 12

Code. 12

 


Client

ClientMainWin

Design

clip_image002

Code

 

using
System;

using
System.Collections.Generic;

using
System.ComponentModel;

using
System.Data;

using
System.Drawing;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

using
System.Windows.Forms;

using
MemoryGameAll.Ifs;

 

namespace
MemoryGameClient

{

    public
partial
class
ClientMainWin
: Form

    {

        Form
current;

        clientConnectionManager
connectionManager;

        bool
isConnected;

        bool
isLogined;

        public ClientMainWin()

        {

            InitializeComponent();

        }

 

      

 

        private void ClientMainWin_Load(object sender,
EventArgs e)

        {

            current = null;

            isConnected = false;

            isLogined = false;

            connectionManager =
new clientConnectionManager(this);

            updateMenuBTNs();

 

 

 

        }

        private void openLoginWin(object sender,
EventArgs e)

        {

           if (current != null)

            {

                if (current is
clientLoginWin)

                {

                    return;

                }

                current.Close();

            }

            current = new
clientLoginWin(
this)
{ Dock = DockStyle.Fill, TopLevel =
false, TopMost = true

};

            mainPanel.Controls.Add(current);

            current.Show();

            updateMenuBTNs();

 

        }

 

        private void openRegWin(object sender,
EventArgs e)

        {

            if (current != null)

            {

                if (current is
registerWin)

                {

                    return;

                }

                current.Close();

            }

            current = new
registerWin(
this)
{ Dock = DockStyle.Fill, TopLevel =
false, TopMost = true

};

            mainPanel.Controls.Add(current);

            current.Show();

            updateMenuBTNs();

        }

 

        public void sendLoginToServer(string userName,string
pass)

        {

            if
(connectionManager.isClientConnected())

            {

                MessageModel message =
new
MessageModel();

                message.msgType =
ProtocolInterface.MsgType.MSG_LOGIN;

                message.userName =
userName;

                message.pass =
pass;

                message.msgStr
=
"";

                message.player
=
null;

                List<int>
lst =
new List<int
> {
1, 2, 6, 5, 7, 8 };

                message.lst =
lst;

                connectionManager.sendMessageToServer(message);

            }

        }

 

        private void connectToServer(object sender,
EventArgs e)

        {

            isConnected =  connectionManager.connectToServer();

            updateMenuBTNs();

            if
(isConnected)

                MessageBox.Show("Connected");

            else

                MessageBox.Show("Connection failed");

        }

        private void
sendMessageToServer(MessageModel message)

        {

 

        }

        private void
updateMenuBTNs()

        {

            btnConnect.Enabled =
!isConnected;

            btnLogin.Enabled = isConnected
&& !isLogined;

            btnRegister.Enabled = isConnected
&& !isLogined;

 

        }

 

        private void
connectionToolStripMenuItem_Click(
object
sender,
EventArgs e)

        {

 

        }

    }

}

clientLoginWin

Design

clip_image004

 

Code

using
System;

using
System.Collections.Generic;

using
System.ComponentModel;

using
System.Data;

using
System.Drawing;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

using
System.Windows.Forms;

 

namespace
MemoryGameClient

{

    public
partial
class
clientLoginWin
: Form

    {

        ClientMainWin
main;

        public clientLoginWin(ClientMainWin main)

        {

            InitializeComponent();

            this.main =
main;

        }

 

        private void btnLogIn_Click(object sender,
EventArgs e)

        {

            string s1 =
txbUserName.Text.Trim();

            string s2 =
txbPass.Text.Trim();

            main.sendLoginToServer(s1,
s2);

        }

 

        private void clientLoginWin_Load(object sender,
EventArgs e)

        {

 

        }

    }

}

clientConnectionManager

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

using
System.Net;

using
System.Net.Sockets;

using
MemoryGameAll.Ifs;

 

namespace
MemoryGameClient

{

    public
class
clientConnectionManager

    {

        private Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

        private int PORT =
7000;

        private int
BUFFER_SIZE = 1048576;

  

        private byte[]
buffer;

        ClientMainWin
main;

        private
bool

isConnected;

        public clientConnectionManager
(ClientMainWin main)

        {

            this.main =
main;

            isConnected = false;

            buffer = new
byte
[BUFFER_SIZE];

        }

 

        public bool
connectToServer()

        {

            try

            {

                clientSocket.Connect("127.0.0.1", PORT);

                isConnected =
clientSocket.Connected;

               

            }

            catch
(Exception ex)

            {

                isConnected = false;

            }

            if
(isConnected)

            {

                clientSocket.BeginReceive(buffer,
0, BUFFER_SIZE, SocketFlags.None, serverMessageCallback,
clientSocket);

              

            }

            return
isConnected;

        }

 

        private void
serverMessageCallback(IAsyncResult ar)

        {

            Socket socket =
(Socket)ar.AsyncState;

 

            int
receivedMessageSize;

 

            try

            {

                receivedMessageSize =
clientSocket.EndReceive(ar);

            }

            catch
(SocketException)

            {

 

                return;

            }

 

            byte[] recBuf = new byte[receivedMessageSize];

            Array.Copy(buffer, recBuf,
receivedMessageSize);

            string msgStr
=
System.Text.Encoding.Default.GetString(recBuf);

            MessageModel message =
ProtocolInterface.DeSerializeMessage(msgStr);

 

          

        }

 

        public bool
isClientConnected()

        {

            return
isConnected;

        }

        public void
sendMessageToServer(MessageModel message)

        {

            string str =
ProtocolInterface.SerializeMessage(message);

            byte[] data
= Encoding.UTF8.GetBytes(str);

            clientSocket.Send(data, 0,
data.Length, SocketFlags.None);

        }

 

      

    }

}

 

 

 

Server

Ifs

ConnectedPlayer

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Net.Sockets;

using
System.Text;

using
System.Threading.Tasks;

 

namespace
MemoryGameAll.Ifs

{

    public
class
ConnectedPlayer

    {

        public PlayerS player { get; set;
}

        public Socket client { get; set;
}

    }

}

ConnectionManager

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

using
System.Net.Sockets;

 

namespace
MemoryGameAll.Ifs

{

    public
class
ConnectionManager

    {

        private
TcpListener listener;

        NetworkStream stream =
default(NetworkStream);

        List<Socket>
clientsList;

        private int
BUFFER_SIZE = 1048576;

        private int PORT =
7000;

        private byte[]
buffer;

        ServerMainWin
main;

        MessgaeHandeling
messgaeHandeling;

        public List<ConnectedPlayer> players {
get;
set
;
}

 

        public ConnectionManager(ServerMainWin main)

        {

            this.main =
main;

            buffer = new
byte
[BUFFER_SIZE];

            listener =  new
TcpListener(System.Net.IPAddress.Any, PORT);

            clientsList = new
List<Socket>();

            players = new
List<ConnectedPlayer>();

            messgaeHandeling =
new MessgaeHandeling(this);

 

        }

        public void
StartServer()

        {

            listener.Start();

            listener.BeginAcceptTcpClient(clientConnected,
null);

           

        }

 

        private void
clientConnected(IAsyncResult ar)

        {

            Socket
socket;

 

            try

            {

                socket =
listener.EndAcceptSocket(ar);

            }

            catch (ObjectDisposedException)
//
I cannot seem to avoid this (on exit when properly closing
sockets)

            {

                return;

            }

 

            clientsList.Add(socket);

            ConnectedPlayer c =
new
ConnectedPlayer();

            c.client =
socket;

 

            players.Add(c);

            socket.BeginReceive(buffer, 0,
BUFFER_SIZE, SocketFlags.None, ReceiveCallback,
socket);

          

            listener.BeginAcceptTcpClient(clientConnected,
null);

            main.updateConnectedClients(getConnectedClients());

        }

 

        public List<string>
getConnectedClients()

        {

 

            List<string>
lst =
new List<string
>();

            foreach (ConnectedPlayer p in
players)

            {

                lst.Add(p.client.RemoteEndPoint.ToString());

            }

            return
lst;

        }

 

        public bool
isListening()

        {

            return
listener.Server.IsBound;

 

        }

 

      

 

        private void
ReceiveCallback(IAsyncResult ar)

        {

            Socket current =
(Socket)ar.AsyncState;

            ConnectedPlayer conncted =
players.Where(x => x.client ==
current).FirstOrDefault();

 

           

 

            int
receivedMessageSize;

 

            try

            {

                receivedMessageSize =
current.EndReceive(ar);

            }

            catch
(SocketException)

            {

                Console.WriteLine("Client forcefully
disconnected"
);

                //
Don't shutdown because the socket may be disposed and its disconnected
anyway.

                current.Close();

                clientsList.Remove(current);

 

                players.Remove(conncted);

                main.updateConnectedClients(getConnectedClients());

                return;

            }

 

            byte[] recBuf = new byte[receivedMessageSize];

            Array.Copy(buffer, recBuf,
receivedMessageSize);

            string msgStr
=
System.Text.Encoding.Default.GetString(recBuf);

            MessageModel message =
ProtocolInterface.DeSerializeMessage(msgStr);

            messgaeHandeling.handelMessage(message,
conncted);

        }

 

      

        public void
sendMessageToClient(ConnectedPlayer connected,MessageModel
message)

        {

            string str =
ProtocolInterface.SerializeMessage(message);

            byte[] data
= Encoding.UTF8.GetBytes(str);

            connected.client.Send(data, 0,
data.Length, SocketFlags.None);

        }

        public void
stopServer()

        {

            listener.Stop();

        }

    }

}

MessageModel

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

 

namespace
MemoryGameAll.Ifs

{

    [Serializable]

    public
class
MessageModel

    {

        public ProtocolInterface.MsgType msgType {
get;
set
;
}

        public string msgStr { get; set;
}

        public string userName { get; set;
}

        public string pass { get; set;
}

        public PlayerS player { get; set;
}

        public List<int> lst { get; set;
}

    }

}

MessgaeHandeling

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

 

namespace
MemoryGameAll.Ifs

{

    public
class
MessgaeHandeling

    {

        dbEntities db =
new
dbEntities();

        ConnectionManager
manager;

        public MessgaeHandeling
(ConnectionManager manager)

        {

            this.manager
= manager;

        }

        public void
handelMessage(MessageModel message, ConnectedPlayer
conncted)

        {

            switch
(message.msgType)

            {

                case
ProtocolInterface.MsgType.MSG_LOGIN:

                    handelLogin(message,
conncted);

                    break;

                case
ProtocolInterface.MsgType.MSG_REGISTER:

                    handelRegister(message,
conncted);

                    break;

            }

        }

        public void
handelLogin(MessageModel message, ConnectedPlayer
conncted)

        {

            string
userName = message.userName;

            PlayerTBL player =
(
from s in db.PlayerTBL where s.email == userName select
s).FirstOrDefault();

            if ( player != null)

            {

                if
(player.password == message.pass)

                {

                    PlayerS playerS =
new
PlayerS();

                    playerS.convertFromPlayerTBL(player);

                    MessageModel mToSend =
new
MessageModel();

                    mToSend.player =
playerS;

                    mToSend.msgType =
ProtocolInterface.MsgType.LOGIN_OK;

                    conncted.player =
playerS;

                    manager.sendMessageToClient(conncted,
mToSend);

                   

                   

                }

                else // wrong password

                {

                   

                    MessageModel mToSend =
new
MessageModel();

                    mToSend.player =
null;

                    mToSend.msgType =
ProtocolInterface.MsgType.LOGIN_ERROR;

                    mToSend.msgStr =
"Wrong
password"
;

                    conncted.player =
null;

                    manager.sendMessageToClient(conncted,
mToSend);

                }

            }

            else // player == null

            {

                MessageModel mToSend =
new
MessageModel();

                mToSend.player =
null;

                mToSend.msgType =
ProtocolInterface.MsgType.LOGIN_ERROR;

                mToSend.msgStr =
"No
User in DB"
;

                conncted.player =
null;

                manager.sendMessageToClient(conncted,
mToSend);

            }

 

        }

        public void
handelRegister(MessageModel message, ConnectedPlayer
conncted)

        {

 

        }

    }

}

PlayerS

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

 

namespace
MemoryGameAll.Ifs

{

    [Serializable]

    public
class
PlayerS

    {

        public int Id { get; set;
}

        public string email { get; set;
}

        public string password { get; set;
}

        public string firstNmae { get; set;
}

        public string lastName { get; set;
}

        public DateTime regDate { get; set;
}

        public void
convertFromPlayerTBL(PlayerTBL p)

        {

            Id =
p.Id;

            email =
p.email;

            password =
p.password;

            firstNmae =
p.firstName;

            lastName =
p.lastName;

            regDate =
p.regDate;

        }

 

    }

}

ProtocolInterface

using
Newtonsoft.Json;

using
System;

using
System.Collections.Generic;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

 

namespace
MemoryGameAll.Ifs

{

    public
static
class
ProtocolInterface

    {

        static JsonSerializer serializer =
new

JsonSerializer();

 

        public enum MsgType

        {

            MSG_LOGIN,

            LOGIN_OK,

            LOGIN_ERROR,

            MSG_REGISTER,

            REGISTER_OK,

            REGISTER_ERROR

        }

        public static string
SerializeMessage(MessageModel message)

        {          

            string str =
JsonConvert.SerializeObject(message);

            return
str;

        }

        public static MessageModel
DeSerializeMessage(
string
msgStr)

        {

            MessageModel message =
JsonConvert.DeserializeObject<MessageModel>(msgStr);

            return
message;

        }

    }

}

ServerMainWin

Design

clip_image006

Code

using
MemoryGameAll.Ifs;

using
System;

using
System.Collections.Generic;

using
System.ComponentModel;

using
System.Data;

using
System.Drawing;

using
System.Linq;

using
System.Text;

using
System.Threading.Tasks;

using
System.Windows.Forms;

using
static

MemoryGameAll.Ifs.ProtocolInterface;

 

namespace
MemoryGameAll

{

    public
partial
class
ServerMainWin
: Form

    {

        ConnectionManager
manager;

        public ServerMainWin()

        {

            InitializeComponent();

        }

 

        private
void
ServerMainWin_Load(
object
sender, EventArgs
e)

        {

            manager = new
ConnectionManager(
this
);

            pictureBox1.BackColor =
Color.Red;

 

            MsgType m1 =
MsgType.LOGIN_OK;

            if (m1 ==
MsgType.LOGIN_OK)

            {

 

            }

 

        }

 

        private void btnStartServer_Click(object sender, EventArgs
e)

        {

            manager.StartServer();

            updateIcon();

        }

        private void
updateIcon()

        {

            if
(manager.isListening())

            {

                pictureBox1.BackColor =
Color.Green;

            }

            else

            {

                pictureBox1.BackColor =
Color.Red;

            }

        }

 

        private void btnStopServer_Click(object sender,
EventArgs e)

        {

            manager.stopServer();

            updateIcon();

        }

 

        public  void
updateConnectedClients(List<
string
>
lst)

        {

            this.Invoke((MethodInvoker) delegate{

                lbxConnectedClients.Items.Clear();

                foreach (string str in
lst)

                {

                    lbxConnectedClients.Items.Add(str);

                }

            });

           

        }

        private void
lbxConnectedClients_SelectedIndexChanged(
object
sender,
EventArgs e)

        {

 

        }

    }

}