我最近尝试为我的XNA游戏添加多人游戏支持,因此我创建了一个控制台应用服务器。它是多线程的,可以同时处理多个客户端。我正在使用TcpListener。问题是我只能从客户端向服务器发送一个数据包。我的意思是我只能有一个
//OnConnect Information about client
SendPackage(client.name, client, (int)PackId.Connect);
当我尝试将其添加到其他位置时,例如我发送ChatHandle()
输入的Console.ReadLine()
方法,它不起作用,服务器也不回复。
这是客户端代码:
public static void SendPackage(string data, Client client, int type)
{
string answer = client.getPayLoadAnswer(data, (short)type);
Console.WriteLine("sent: {0}", data);
Console.WriteLine("recieved: {0}", answer);
}
getPayloadAnswer()方法:
public string getPayLoadAnswer(string payLoad, short id)
{
List<byte> payloadData = new List<byte>();
payloadData.AddRange(BitConverter.GetBytes(id));
payloadData.AddRange(MakeString(payLoad));
client.GetStream().Write(payloadData.ToArray(), 0, payloadData.Count);
client.GetStream().Read(new byte[2], 0, 2);
string answer = ReadString(client);
payloadData.Clear();
return answer;
}
private byte[] MakeInt(int i)
{
return BitConverter.GetBytes(i);
}
private byte[] MakeString(string input)
{
List<byte> data = new List<byte>();
data.AddRange(MakeInt(Encoding.ASCII.GetByteCount(input)));
data.AddRange(Encoding.ASCII.GetBytes(input));
return data.ToArray();
}
private int ReadInt(TcpClient client)
{
byte[] data = new byte[4];
client.GetStream().Read(data, 0, 4);
return BitConverter.ToInt32(data, 0);
}
private string ReadString(TcpClient client)
{
byte[] data = new byte[ReadInt(client)];
client.GetStream().Read(data, 0, data.Length);
return Encoding.ASCII.GetString(data);
}
服务器端代码:
private void HandleClient(TcpClient client)
{
byte[] packetIDData = new byte[2];
client.GetStream().Read(packetIDData, 0, 2);
ushort packetID = BitConverter.ToUInt16(packetIDData, 0);
//Console.WriteLine("packet id: {0}", packetID);
switch (packetID)
{
case 0:
{
Console.WriteLine("Player {0} connected", ReadData(client));
RespondToClient(client, "Successfuly connected to server!");
Players.Add(client, ReadData(client));
}
break;
case 1:
{
Console.WriteLine("{0} said: {1}", GetUsername(Players, client), ReadData(client));
RespondToClient(client, "Sent message successfuly!");
}
break;
default:
{
Console.WriteLine("Unknow packet info");
RespondToClient(client, "Unknow packet info");
}
break;
}
client.Close();
}
private void RespondToClient(TcpClient client, string response)
{
List<byte> backData = new List<byte>();
backData.AddRange(BitConverter.GetBytes((short)0));
backData.AddRange(BitConverter.GetBytes(Encoding.ASCII.GetByteCount(response)));
backData.AddRange(Encoding.ASCII.GetBytes(response));
client.GetStream().Write(backData.ToArray(), 0, backData.ToArray().Length);
}
private string ReadData(TcpClient client)
{
byte[] data = new byte[4];
client.GetStream().Read(data, 0, 4);
int length = BitConverter.ToInt32(data, 0);
data = new byte[length];
client.GetStream().Read(data, 0, length);
return Encoding.ASCII.GetString(data);
}
谢谢!