客户端服务器套接字C# [英] Client server socket C#
问题描述
我正在使用套接字C#。我已经使用套接字实现了客户端服务器应用程序,但是问题是客户端没有收到服务器发送的所有数据。
这是客户端应用程序代码。我应该怎么做才能接收服务器发送的所有数据?
strRecieved =;
Socket soc =新的Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint端点=新的IPEndPoint(IPAddress.Parse( 127.0.0.1),9001);
soc.Connect(endPoint);
byte [] msgBuffer = Encoding.Default.GetBytes(path);
soc.Send(msgBuffer,0,msgBuffer.Length,0);
byte [] buffer = new byte [2000];
int rec = soc.Receive(buffer);
strRecieved = String.Format(Encoding.Default.GetString(buffer));
首先。如果您要实现某种流功能(tcp / udp / file),则应考虑使用某种协议。
什么是协议?这只是流数据时要使用的方案。示例:
[4字节-长度] [长度字节-消息] [1字节-终止指示符]
知道该协议后,您可以像这样简单地读取所有传入的字节:
byte [] buffer = new字节[4];
stream.ReadBytes(buffer,0,4); //将其转换为int并读取其余的
int packetLen = BitConverter.ToInt32(buffer,0);
buffer = new byte [packetLen];
stream.ReadBytes(buffer,0,buffer.Length); //发送的所有字节
请记住,发送前必须减去长度4个字节
编辑:
有关发送和接收的简单示例数据使用共享的协议。
// sender.cs
string _stringToSend = some花式字符串;
byte [] encodeString = Encoding.UTF8.GetBytes(_stringToSend);
List< byte>缓冲区=新的List< byte>();
buffer.AddRange(BitConverter.GetBytes(encodedString.Length));
buffer.AddRange(encodedString);
netStream.WriteBytes(buffer.ToArray(),0,buffer.Count);
// netStream以协议[@LEN-4Bytes] [@ MSG-@LENBytes]发送消息
//简而言之:5ABCDE
// receive.cs
byte [] buffer = new byte [sizeof(int)];
netStream.ReadBytes(buffer,0,buffer.Length);
//接收者得到消息的长度,例如5
int dataLen = BitConverter.ToInt32(缓冲区,0);
buffer = new byte [dataLen];
//现在我们可以读取一条实际的消息,因为我们知道它的长度
netStream.ReadBytes(buffer,0,buffer.Length);
string receiveString = Encoding.UTF8.GetString(buffer);
//收到的字符串等于某些特殊字符串
使其更简单
此技术会强制您使用所需的协议,在本示例中为:
前4个字节 sizeof(int)
表示传入数据包的长度
每一个字节都是您的数据包,直到结尾。 / p>
所以现在您应该制作 ProtocolHelper
对象:
公共静态类ProtocolHelper
{
public byte [] PackIntoProtocol(字符串消息)
{
List< byte>结果=新的List< byte>();
byte [] messageBuffer = Encoding.UTF8.GetBytes(message);
result.AddRange(BitConverter.GetBytes(messageBuffer.Length),0); //这是协议的第一部分(消息的长度)
result.AddRange(messageBuffer); //这是实际的消息
返回结果.ToArray();
}
公共字符串UnpackProtocol(byte [] buffer)
{
return Encoding.UTF8.GetString(buffer,0,buffer.Length);
}
}
现在(取决于您选择的阅读方法通过网络),您必须发送和接收消息。
// sender.cs
string meMessage =网络消息1;
byte [] buffer = ProtocolHelper.PackIntoProtocol(meMessage);
socket.Send(buffer,0,buffer.Length,0);
// receiver.cs
字符串消息= string.Empty;
byte [] buffer = new byte [sizeof(int)]; //或只是新的byte [4];
int收到= socket.Receive(buffer);
if(received == sizeof(int))
{
int packetLen = BitConverter.ToInt32(buffer); //我们消息的大小
buffer =新字节[packetLen] ;
已收到= socket.Receive(buffer);
if(packetLen == receive)//我们有完整的缓冲区
{
message = PacketHelper.UnpackProtocol(buffer);
}
}
Console.WriteLine(message); //输出:网络消息1
I am working on socket C#. I've implemented a client server application using socket, but the problem is that the client doesn't receive all data sent by the server.
Here is the client application code. What should I do so that it would receive all data sent by the server?
strRecieved = "";
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
soc.Connect(endPoint);
byte[] msgBuffer = Encoding.Default.GetBytes(path);
soc.Send(msgBuffer, 0, msgBuffer.Length, 0);
byte[] buffer = new byte[2000];
int rec = soc.Receive(buffer);
strRecieved = String.Format(Encoding.Default.GetString(buffer));
First of all. If you're implementing some kind of streaming feature ( tcp/udp/file ) you should consider using some kind of protocol.
What is a protocol? It's just a scheme to use when streaming data. Example:
[4Bytes - length][lengthBytes - message][1Byte - termination indicator]
Knowing the protocol you can read all of the incoming bytes simply as such :
byte[] buffer = new byte[4];
stream.ReadBytes(buffer, 0, 4); // cast that to int and read the rest
int packetLen = BitConverter.ToInt32(buffer, 0);
buffer = new byte[packetLen];
stream.ReadBytes(buffer, 0, buffer.Length); // all bytes that was sent
Remember that you have to subtract thease 4 bytes in the length before sending the message.
EDIT:
Simple example on how to send and receive data using shared protocol.
// sender.cs
string _stringToSend = "some fancy string";
byte[] encodedString = Encoding.UTF8.GetBytes(_stringToSend);
List<byte> buffer = new List<byte>();
buffer.AddRange(BitConverter.GetBytes(encodedString.Length));
buffer.AddRange(encodedString);
netStream.WriteBytes(buffer.ToArray(), 0, buffer.Count);
// netStream sent message in protocol [@LEN - 4Bytes][@MSG - @LENBytes]
// simply speaking something like: 5ABCDE
// receiver.cs
byte[] buffer = new byte[sizeof(int)];
netStream.ReadBytes(buffer, 0, buffer.Length);
// receiver got the length of the message eg. 5
int dataLen = BitConverter.ToInt32(buffer, 0);
buffer = new byte[dataLen];
// now we can read an actual message because we know it's length
netStream.ReadBytes(buffer, 0, buffer.Length);
string receivedString = Encoding.UTF8.GetString(buffer);
// received string is equal to "some fancy string"
Making it simpler
This technique forces you to use desired protocol which in this example will be :
First 4 bytes sizeof(int)
are indicating the length of the incoming packet
Every byte further is your packet until the end.
So right now you should make ProtocolHelper
object:
public static class ProtocolHelper
{
public byte[] PackIntoProtocol(string message)
{
List<byte> result = new List<byte>();
byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
result.AddRange(BitConverter.GetBytes(messageBuffer.Length), 0); // this is the first part of the protocol ( length of the message )
result.AddRange(messageBuffer); // this is actual message
return result.ToArray();
}
public string UnpackProtocol(byte[] buffer)
{
return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}
}
Now ( depending on method you've chosen to read from network ) you have to send and receive your message.
// sender.cs
string meMessage = "network message 1";
byte[] buffer = ProtocolHelper.PackIntoProtocol(meMessage);
socket.Send(buffer, 0, buffer.Length, 0);
// receiver.cs
string message = string.Empty;
byte[] buffer = new byte[sizeof(int)]; // or simply new byte[4];
int received = socket.Receive(buffer);
if(received == sizeof(int))
{
int packetLen = BitConverter.ToInt32(buffer);// size of our message
buffer = new byte[packetLen];
received = socket.Receive(buffer);
if( packetLen == received ) // we have full buffer
{
message = PacketHelper.UnpackProtocol(buffer);
}
}
Console.WriteLine(message); // output: "network message 1"
这篇关于客户端服务器套接字C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!