我将此数据包类(.dll)用于我的多线程客户端 - 服务器应用程序。 但我不知道如何使用我的代码发送字符串 - 请帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net.NetworkInformation;
namespace ServerData
{
[Serializable]
public class Packet
{
public List<string> Gdata;
public int packetInt;
public bool packetBool;
public string senderID;
public PacketType packetType;
public Packet(PacketType type, string senderID)
{
Gdata = new List<string>();
this.senderID = senderID;
this.packetType = type;
}
public Packet(byte[] packetbytes)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(packetbytes);
Packet p = (Packet)bf.Deserialize(ms);
ms.Close();
this.Gdata = p.Gdata;
this.packetInt = p.packetInt;
this.packetType = p.packetType;
this.senderID = p.senderID;
this.packetBool = p.packetBool;
}
public byte[] ToBytes()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, this);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
public static string GetIP4Address()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress i in ips)
{
if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return i.ToString();
}
}
return "127.0.0.1";
}
public static string GetIP6Address()
{
string macAddresses = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
}
public enum PacketType
{
Registration,
Command,
Download,
Inquiry,
Reponse,
Confirmation
}
}
服务器/客户端中的发送功能:
public void SendRegistrationPacket() // for example this send an packet from the type registration but in this moment i can "know" whats in the packet by "asking" what type it is...
{
Packet p = new Packet(PacketType.Registration, id);
clientSocket.Send(p.ToBytes()); //clientSocket is the socket where the client is connected^^
}
传入数据的管理器(不是只读处理引用的数据):
void DataManager(Packet p)
{
switch (p.packetType)
{
case PacketType.Registration:
listBox1.Items.Add("Got Registration Packet");
listBox1.Items.Add("Sending Registration...");
break;
}
}
我如何发送字符串并用这些数据包“编码”它们?
答案 0 :(得分:0)
此课程提供public List<string> Gdata;
。您可以向此对象添加任意数量的字符串,序列化程序将负责处理它。所以例如你可以写
Packet p = new Packet(PacketType.Command, 123);
p.Gdata.Add("SomeString which I want to execute");
clientSocket.Send(p.ToBytes());
在接收端,您将反序列化Packet
对象并照常使用Gdata
字段。
byte[] received = new byte[1024];
int num_received = someSocket.Receive(received);
Packet decoded = new Packet(received.Take(num_received).ToArray());
Console.WriteLine("The first string in the list: " + decoded.Gdata[0]);