110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 程序入口
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//创建一个Socket
foreach (Address addressValue in GetAddress())
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接到指定服务器的指定端口
try
{
socket.Connect(addressValue.IP, addressValue.Port);
Console.WriteLine("{0}:{1}:Conneted...." + "\r\n", addressValue.IP, addressValue.Port);
//实现接受消息的方法
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
/// <summary>
/// 异步接收数据
/// </summary>
/// <param name="ar"></param>
public static void ReceiveMessage(IAsyncResult ar)
{
try
{
var socket = ar.AsyncState as Socket;
var length = socket.EndReceive(ar);
string Ip = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
int port = (socket.RemoteEndPoint as IPEndPoint).Port;
//分多次接收
byte[] reallData = new byte[length];
Array.Copy(buffer, reallData, reallData.Length);
string data = BitConverter.ToString(reallData) + "\r\n";
StatisticsData(data, Ip, port);
//接收下一个消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 异步接收数据
/// </summary>
/// <param name="ar"></param>
public static void ReceiveMessage(IAsyncResult ar)
{
try
{
var socket = ar.AsyncState as Socket;
var length = socket.EndReceive(ar);
//分多次接收
byte[] reallData = new byte[length];
//Array.Copy(buffer, reallData, reallData.Length);
string data = BitConverter.ToString(reallData) + "\r\n";
StatisticsData(data);
//接收下一个消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
var socket = ar.AsyncState as Socket;
var length = socket.EndReceive(ar);
//分多次接收
byte[] reallData = new byte[length];
Array.Copy(buffer, reallData, reallData.Length);
string data = BitConverter.ToString(reallData) + "\r\n";
StatisticsData(data);
我的一台设备由于数据量比较大,可能一次的数据收取过来的时候,是分了4次左右发送的
那么 var length = socket.EndReceive(ar);这个地方接收的时候 我看了一下 最大是1024
我这里该如何确保一次接收的数据是一个完整的包?该如何合并或者判断 谢谢~
static List<Socket> cs = new List<Socket>();
static void Main(string[] args)
{
//创建一个Socket
foreach (Address addressValue in GetAddress())
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
cs.Add(socket);
try
{
socket.Connect(addressValue.IP, addressValue.Port);
Console.WriteLine("{0}:{1}:Conneted...." + "\r\n", addressValue.IP, addressValue.Port);
//实现接受消息的方法
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.WriteLine("....................按任意键结束");
Console.Read();
}