我正在搜索包含以下内容的Streamclass: - 发送/接收字节数组的方法 - 发送/接收字符串的方法
我发现的唯一一个类是NetworkStream。但是NetworkStream-Class的缺点是,如果我想发送一个字符串,我必须将此字符串转换为字节数组并发送此字节数组,因为没有直接发送字符串的方法。 另一方面,像Streamwriter这样的类有发送/接收字符串的方法,但没有发送/接收字节数组的方法。
如果我尝试将这两个Streamclasses组合在一起:
TcpClient clientConnection = new TcpClient();
NetworkStream nws = clientConnection.GetStream();
StreamWriter sw = new StreamWriter(nws);
sw.writeLine("ABC");
sw.Flush();
nws.Write(byteArray, 0, lengthToSend);
我得到了很多奇怪的错误(比如byteArray不会在另一端完全收到),因为我在这里以两种不同的方式使用相同的一个流。
那么,我必须使用NetworkStream-Class作为我的计划还是存在更好的方法?
答案 0 :(得分:0)
我有同样的问题,关键是对方不知道你发送的是字节数组或字符串,所以我所做的就是为每个msg特别是在处理严肃的服务器/客户端应用程序时放一个标题因为你将拥有多个数据(用户信息,请求信息,回复信息等)
我正在使用streamwriter发送和streamreader接收,但我也在使用线程 只要客户端已连接,连接就会保持打开状态,因此我将其声明为
这是我的代码的完整示例
public class Client
{
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
private Thread thrMessaging;
private string UserName = "UK";
private byte Tries = 0;
private bool Connected = false;
public void Connect()
{
if (!Connected)
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
string User = localIPs[0].ToString();
string ServIP = "127.0.0.1";//change this to your server ip
InitializeConnection(ServIP, User);
}
else
{
CloseConnection("Disconnected at user's request.");
}
}
private void InitializeConnection(string ServIp, string User)
{
IPAddress ipAddr = IPAddress.Parse(ServIp);
tcpServer = new TcpClient();
try
{
tcpServer.Connect(ipAddr, 1986);//change that 1986 to your server port
}
catch
{
if (Connected) CloseConnection("");
MessageBox.Show("Connecteing to " + ServIp + "\r\nServer is Down ... Try nomber " + Tries); return;
}
Connected = true;
UserName = User;
swSender = new StreamWriter(tcpServer.GetStream());
swSender.WriteLine(User);
swSender.Flush();
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
}
private void ReceiveMessages()
{
srReceiver = new StreamReader(tcpServer.GetStream());
string ConResponse = srReceiver.ReadLine();
if (ConResponse[0] == '1')
{
}
else
{
string Reason = "Not Connected: ";
Reason += ConResponse.Substring(2, ConResponse.Length - 2);
return;
}
while (Connected)
{
try
{
string NewMsg = srReceiver.ReadLine();
if (NewMsg != null && NewMsg != "")
PacketHandler.HandlePacket(NewMsg, this);
}
catch { }
}
}
public void CloseConnection(string Reason)
{
try
{
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
catch { }
}
public void SendMessage(string Msg)
{
if (Msg.Length >= 1)
{
try
{
Tries++;
swSender.WriteLine(Msg);
swSender.Flush();
Tries = 0;
}
catch
{
if (Tries < 5)
{
try
{
CloseConnection("No connection made");
Connect();
}
catch { }
SendMessage(Msg);
}
else { MessageBox.Show("Connecting to server faild for 5 tries"); Tries = 0; }
}
}
}
然后在数据包处理程序中,我处理以检查客户端收到的数据类型
类似这样的事情
public static void HandlePacket(string MsgRec, Client Client)
{
string[] Info = MsgRec.Split('|');
string Type = Info[0];
if (Type == "")
{
return;
}
string subtype = Info[1];
int TLen = Type.Length + subtype.Length + 2;
string Data = MsgRec.Remove(0, TLen);//this is the main data the server sent
ushort PacketType = ushort.Parse(Type);
ushort SubType = ushort.Parse(subtype);
switch ((Structs.PacketType)PacketType)
{
case Structs.PacketType.Login:
{
//do your stuff here
break
}
case Structs.PacketType.Image:
{
//convert the Data back to byte array then get the image out from it
break
}
case Structs.PacketType.ByteArray:
{
//convert the Data back to byte array
break
}
}
}
我知道它有点混乱而不是完美的方式,但它对我有用 并记住在另一方面发送内容时你需要添加数据包类型和子类型,或者如果你做一些简单的话,只需添加任何分割器的头文件
最后:我认为如果你发送小数据包长度
,使用套接字和数据包将会容易得多