if you show us that what exception was caught when something goes wrong.... then we can help definitely.....
I guess your are havig a loop con client side like...
ASCIIEncoding encoder = new ASCIIEncoding();
int bytesRead = 0;
byte[] receiveBuffer = new byte[1000];
string data;
while (true)
{
try
{
bytesRead = cl.GetStream().Read(receiveBuffer, 0, nBuff);
data = encoder.GetString(receiveBuffer, 0, bytesRead);
switch(data)
{
case "spawn":
string namee = sr.ReadLine();
int index = GetIndexByName(namee);
players[index].xpos = int.Parse(sr.ReadLine());
players[index].ypos = int.Parse(sr.ReadLine());
players[index].pb = new PictureBox();
players[index].pb.Location = new Point(players[index].xpos, players[index].ypos);
players[index].pb.SizeMode = PictureBoxSizeMode.StretchImage;
players[index].pb.Size = new Size(50, 50);
players[index].pb.Image = players[index].img;
BeginInvoke((MethodInvoker)delegate { Controls.Add(players[index].pb); });
break;
}
}
catch (Exception ex)
{
}
}
And the problem is (as i guess.. your server is multi-threaded)
Take a case (can be simulated)
1. You send "spawn" (
PacketSender(pig, "spawn");
) to say client1 from server and thread switched and same time client1 received "spawn" and it goes to the
case "spawn" :
and blocked on
string namee = sr.ReadLine();
line....
2. Then some other thread send some data to client1 which is not a name while client1 expecting a name... and you got a bug.
3. May be same thing happened on when client1 expecting a number(as in string) and client1 parse your string variable to integer (
players[index].xpos = int.Parse(sr.ReadLine());
) where
sr.ReadLine()
not containing a number.... bug.....
problem is in sending sequence..
Another thing, you are sending PlayersInGame object int 3 send calls (means all three call contain related data and there must be 3 receive calls in server side ), but you can send it in only in one call... I am not saying you send like
PacketSender(pig, players[i].Name + players[i].pos + players[i].pos);
No not like that.....
Actually one of the most common requirement in distributed application (like your game) is sending objects across network... And c sharp have a simple solutions:--
1. serialize your object
2. Send it on network,
3. Receive it and deserialize and cast it to your desired object...
It will make your code bullet-proof....
You can also use another solution..
use RPC it will make an easiest way to communicate in your application..
Don't forget voting..
well if you still having problem send me your code at ashishtyagi40@gmail.com, and i will definitely cooperate you friend...
Most important thing catch your exception and log it into a file is the key to debug a multi-threaded application, so always log your exception along with class.function_name, line_no and time_stamp
:cool: