本文整理汇总了C#中System.Net.Sockets.Socket.EndReceive方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.EndReceive方法的具体用法?C# Socket.EndReceive怎么用?C# Socket.EndReceive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.EndReceive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BeginReceiveServer
private static void BeginReceiveServer(Socket client)
{
var buffer = new byte[0xFFFF];
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, result =>
{
OnReceiveServer(buffer, client.EndReceive(result));
BeginReceiveServer(client);
}, buffer);
}
示例2: BeginReceiveClient
private static void BeginReceiveClient(Socket server)
{
var buffer = new byte[0xFFFF];
server.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, result =>
{
OnReceiveClient(buffer, server.EndReceive(result));
BeginReceiveClient(server);
}, buffer);
}
示例3: DiscoverAsync
public static async Task<bool> DiscoverAsync(object state = null)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1900);
byte[] outBuf = Encoding.ASCII.GetBytes(BroadcastPacket);
byte[] inBuf = new byte[4096];
int tries = MaxTries;
while (--tries > 0)
{
try
{
TaskFactory factory = new TaskFactory();
sock.ReceiveTimeout = DiscoverTimeout;
await factory.FromAsync(sock.BeginSendTo(outBuf, 0, outBuf.Length, 0, endpoint, null, null), end =>
{
sock.EndSendTo(end);
}).ConfigureAwait(false);
var ar = sock.BeginReceive(inBuf, 0, inBuf.Length, 0, null, null);
if (ar == null) throw new Exception("ar is null");
int length = await factory.FromAsync(ar, end => sock.EndReceive(end)).ConfigureAwait(false);
string data = Encoding.ASCII.GetString(inBuf, 0, length).ToLowerInvariant();
var match = ResponseLocation.Match(data);
if (match.Success && match.Groups["location"].Success)
{
System.Diagnostics.Debug.WriteLine("Found UPnP device at " + match.Groups["location"]);
string controlUrl = GetServiceUrl(match.Groups["location"].Value);
if (!string.IsNullOrEmpty(controlUrl))
{
_controlUrl = controlUrl;
System.Diagnostics.Debug.WriteLine("Found control URL at " + _controlUrl);
return true;
}
}
}
catch (Exception ex)
{
// ignore timeout exceptions
if (!(ex is SocketException && ((SocketException) ex).ErrorCode == 10060))
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
return false;
}
示例4: Run
public void Run()
{
int len_receive_buf = 4096;
int len_send_buf = 4096;
byte[] receive_buf = new byte[len_receive_buf];
byte[] send_buf=new byte[len_send_buf];
int cout_receive_bytes;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Blocking = false;
IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
socket.Bind(new IPEndPoint(IPAddress.Parse(IPHost.AddressList[0].ToString()),5000));
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
byte[] IN = new byte[4] { 1, 0, 0, 0 };
byte[] OUT = new byte[4];
int SIO_RCVALL = unchecked((int)0x98000001);
int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT);
while (true)
{
IAsyncResult ar = socket.BeginReceive(receive_buf, 0, len_receive_buf, SocketFlags.None, null, this);
cout_receive_bytes = socket.EndReceive(ar);
Receive(receive_buf, cout_receive_bytes);
}
}
示例5: WaitForCommand
protected void WaitForCommand(Socket socket, CommandReceivedEventHandler callback, byte[] commandBuffer, int commandBufferSize = 1024)
{
if (commandBuffer == null)
{
commandBuffer = new byte[commandBufferSize];
}
try
{
socket.BeginReceive(commandBuffer, 0, commandBufferSize, 0,
asyncResult =>
{
int bytesRead;
try
{
bytesRead = socket.EndReceive(asyncResult);
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
return;
}
if (bytesRead <= 0)
{
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
return;
}
var command = DongleEncoding.Default.GetString(commandBuffer, 0, bytesRead);
if (callback != null)
{
try
{
callback(command);
}
catch (ThreadAbortException)
{
//Treadh abortada. Nada a fazer
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
else
{
throw;
}
}
}
},
null);
}
catch (Exception)
{
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
}
}
示例6: ReceiveCallback
public void ReceiveCallback(IAsyncResult ar)
{
try
{
// Fetch a user-defined object that contains information
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
// Received byte array
byte[] buffer = (byte[])obj[0];
// A Socket to handle remote host communication.
handler = (Socket)obj[1];
// Received message
string content = string.Empty;
// The number of bytes received.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
content += Encoding.Unicode.GetString(buffer, 0,
bytesRead);
// If message contains "<Client Quit>", finish receiving
if (content.IndexOf("<Client Quit>") > -1)
{
// Convert byte array to string
string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));
//this is used because the UI couldn't be accessed from an external Thread
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
tbAux.Text = "Read " + str.Length * 2 + " bytes from client.\n Data: " + str;
}
);
}
else
{
// Continues to asynchronously receive data
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallback), obj);
}
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
tbAux.Text = content;
}
);
}
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
示例7: OnReceiveData
/// <summary>
/// Process data received from the socket.
/// </summary>
/// <param name="ar"></param>
public void OnReceiveData( IAsyncResult ar )
{
_socket = (Socket) ar.AsyncState;
if (_socket == null || !_socket.Connected)
return;
try
{
int bytesReceived = _socket.EndReceive(ar);
if( bytesReceived > 0)
{
string buffer = Encoding.ASCII.GetString(_inBuffer, 0, 1024);
AddTerminalText( buffer );
_inBuffer = null;
}
SetupReceiveCallback(_socket);
}
catch( SocketException ex)
{
MessageBox.Show("Error Receiving Data: " + ex.ToString());
if (_socket != null)
_socket.Close();
EnableConnect(true);
}
catch( Exception ex)
{
MessageBox.Show(ex.Message, "Error processing receive buffer!");
return;
}
}
示例8: HandleProcess
public void HandleProcess(int p)
{
//trimite cerere de statistici si primeste raspuns pe un socket
//lock, seteaza resetEvent-ul portului respectiv cand termina
//lock , adauga statisticile in JobStatistics
ProcessStatistics ps = null;
// try
// {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ip = System.Net.IPAddress.Parse("127.0.0.1");
System.Net.IPEndPoint remEP = new System.Net.IPEndPoint(ip, (Int32)p);
sock.Connect(remEP);
byte[] data = System.Text.Encoding.ASCII.GetBytes("2");
sock.Send(data);
byte[] recvData = new byte[4048];
sock.BeginReceive(recvData, 0, recvData.Length, SocketFlags.None,
delegate(IAsyncResult res)
{
int read = sock.EndReceive(res);
String response = System.Text.Encoding.UTF8.GetString(recvData);
string[] param1 = response.Split('_');
int[] param = new int[param1.Count()];
for (int i = 0; i < param1.Count(); i++)
{
param[i] = Int32.Parse(param1[i]);
}
ps = new ProcessStatistics(param[1], param[2], param[3], param[4], param[5]
, param[6], param[7], param[8], param[9], DateTime.Now, DateTime.Now);
lock (this._jobStatistics)
{
if (ps != null)
this._jobStatistics.ProcessStatisticsList.Add(ps);
}
/*If all the sockets finished waiting, release the main thread.*/
if (--this._waiting <= 0)
{
try
{
_event.Set();
}
catch (Exception ex)
{
}
}
}, null);
/*sock.ReceiveAsync(new SocketAsyncEventArgs()
{
});*/
//}
/*catch (Exception ex)
{
//;
}*/
}
示例9: BeginReceive
private void BeginReceive(IAsyncResult iar)
{
try
{
if (isConnected())
{
client = (Socket)iar.AsyncState;
int bytesRead = client.EndReceive(iar);
if (bytesRead != 0)
{
string message = Encoding.ASCII.GetString(data, 0, bytesRead);
msgReceived(this, new MessageReceivedEventArgs(message));
}
client.BeginReceive(data, 0, 2048, SocketFlags.None, new AsyncCallback(BeginReceive), client);
}
}
catch (SocketException ex)
{
Console.WriteLine(String.Format("{0} {1}", ex.Message, ex.ErrorCode));
if (receiveFailed != null)
receiveFailed(this, new EventArgs());
}
}
示例10: receivePacketAndHandle
private void receivePacketAndHandle(Socket clientSocket, IAsyncResult result)
{
int packetLen = clientSocket.EndReceive(result);
byte[] packet = new byte[packetLen];
Buffer.BlockCopy(buffer, 0, packet, 0, packetLen);
handler.Handle(packet);
}
示例11: extractData
/// <summary>
/// Take the incoming data from a client and convert it into a TFMS_Data object
/// </summary>
/// <param name="socket">the socket that connects the server and the client</param>
/// <param name="info">the information about the client from the socket</param>
/// <param name="result">the result of the connection attempt</param>
/// <returns></returns>
private TFMS_Data extractData(Socket socket, TFMS_ClientInfo info, IAsyncResult result)
{
try
{
int numBytesReceived = socket.EndReceive(result); // EndReceive returns how many bytes were received
byte[] temp = new byte[numBytesReceived];
// the buffer might not be used for the first Received message so check if it exists
// otherwise use the default buffer
if (info == null || info.buffer == null)
Array.Copy(byteData, temp, numBytesReceived);
else
Array.Copy(info.buffer, temp, numBytesReceived);
// parse the bytes and turn it into a TFMS_Data object
return new TFMS_Data(temp);
}
catch (SocketException)
{
// if something goes wrong, logoff the client
return new TFMS_Data(TFMS_Command.Logout, null, getNamefromSocket(socket));
}
}
示例12: NetworkReceive
private void NetworkReceive(SocketPurpose Purpose, Socket NetworkSocket, IAsyncResult ar)
{
try
{
int length = NetworkSocket.EndReceive(ar);
if (length > 0)
{
ProcessData Processor = null;
if (Purpose == SocketPurpose.Debug)
Processor = debugProcessor.Process;
else if (Purpose == SocketPurpose.Control)
Processor = controlProcessor.Process;
if (Processor != null)
{
Processor.BeginInvoke(networkBuf, length,
delegate(IAsyncResult AsR) { ProcessFinish(Processor, Purpose, NetworkSocket, AsR); },
null);
}
else
{
throw new Exception("In network receive with invalid purpose, this should not happen");
}
}
else
{
Console.WriteLine("{0} connection closed", SocketName(Purpose));
DeviceInUse = false;
StartListen();
}
}
catch (SocketException e)
{
OnSocketException(Purpose, NetworkSocket, e);
}
catch (ObjectDisposedException)
{
OnObjectDisposedException(Purpose, NetworkSocket);
}
}
示例13: Receive
private IEnumerator<ITask> Receive(Socket socketClient, NodeId nodeid) {
if (socketClient == null) {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: Receive: socket == null!!!"));
yield break;
}
if (!socketClient.Connected) {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: << {0} receive, but client is not connected", socketClient.RemoteEndPoint));
HandleRemoteClosing(socketClient);
yield break;
}
while (socketClient != null && m_ReloadConfig.State < ReloadConfig.RELOAD_State.Exit) {
byte[] buffer = new byte[ReloadGlobals.MAX_PACKET_BUFFER_SIZE * ReloadGlobals.MAX_PACKETS_PER_RECEIVE_LOOP];
var iarPort = new Port<IAsyncResult>();
int bytesReceived = 0;
try {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET, String.Format("SimpleFLM: << {0} BeginReceive", socketClient == null ? "null" : socketClient.RemoteEndPoint.ToString()));
socketClient.BeginReceive(
buffer,
0,
buffer.Length,
SocketFlags.None, iarPort.Post, null);
}
catch (Exception ex) {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: << {0} BeginReceive", socketClient == null ? "null" : socketClient.RemoteEndPoint.ToString()) + ex.Message);
}
yield return Arbiter.Receive(false, iarPort, iar => {
try {
if (iar != null)
bytesReceived = socketClient.EndReceive(iar);
}
catch (Exception ex) {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO,
String.Format("SimpleFLM: << {0} Receive: {1} ",
nodeid == null ? "" : nodeid.ToString(), ex.Message));
}
if (bytesReceived <= 0) {
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
String.Format("SimpleFLM: << {0} Receive: lost connection, closing socket",
socketClient.RemoteEndPoint));
HandleRemoteClosing(socketClient);
socketClient.Close();
socketClient = null;
return;
}
m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
String.Format("SimpleFLM: << {0} Read {1} bytes from {2}",
socketClient.RemoteEndPoint,
bytesReceived, nodeid == null ? "" : nodeid.ToString()));
m_ReloadConfig.Statistics.BytesRx = (UInt64)bytesReceived;
#if CONNECTION_MANAGEMENT
/* beginn connection management */
long bytesProcessed = 0;
SimpleOverlayConnectionTableElement socte = null;
if (ReloadGlobals.Framing) {
foreach (KeyValuePair<string, SimpleOverlayConnectionTableElement> pair in m_connection_table) {
if (socketClient == pair.Value.AssociatedSocket) {
socte = pair.Value;
break;
}
}
if (socte == null)
socte = new SimpleOverlayConnectionTableElement();
Array.Resize(ref buffer, bytesReceived);
buffer = analyseFrameHeader(socte, buffer);
bytesReceived = buffer.Length;
}
ReloadMessage reloadMsg = null;
if (buffer != null) {
reloadMsg = new ReloadMessage(m_ReloadConfig).FromBytes(buffer,
ref bytesProcessed, ReloadMessage.ReadFlags.full);
}
if (socketClient != null && reloadMsg != null) {
if (nodeid == null)
nodeid = reloadMsg.LastHopNodeId;
if (nodeid != null)
if (m_connection_table.ContainsKey(nodeid.ToString())) {
SimpleOverlayConnectionTableElement rcel = m_connection_table[
nodeid.ToString()];
rcel.LastActivity = DateTime.Now;
}
else {
SimpleOverlayConnectionTableElement rcel = socte;
if (rcel == null)
rcel = new SimpleOverlayConnectionTableElement();
rcel.NodeID = reloadMsg.LastHopNodeId;
rcel.AssociatedSocket = socketClient;
//.........这里部分代码省略.........
示例14: ReceiveCallback
public void ReceiveCallback(IAsyncResult ar)
{
try
{
// Fetch a user-defined object that contains information
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
// Received byte array
byte[] buffer = (byte[])obj[0];
// A Socket to handle remote host communication.
handler = (Socket)obj[1];
// Received message
string content = string.Empty;
// The number of bytes received.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
content += Encoding.Unicode.GetString(buffer, 0,
bytesRead);
// Continues to asynchronously receive data
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallback), obj);
/*
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
tbAux.Text = content;
}
);*/
}
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
示例15: WaitForFile
protected void WaitForFile(Socket socket, FileReceivedEventHandler fileReceivedCallback, int fileSize, int bufferSize = DefaultBufferSize, byte[] previousPart = null, int currentPart = 0, int totalParts = 1)
{
if (currentPart == 0)
{
totalParts = (int)Math.Ceiling(Convert.ToDouble(fileSize) / Convert.ToDouble(bufferSize));
}
var buffer = new byte[bufferSize];
try
{
SocketError errorCode;
socket.BeginReceive(buffer, 0, bufferSize, 0, out errorCode, asyncResult =>
{
byte[] newPart;
Debug.WriteLine("RECEIVING FILE " + currentPart + "/" + totalParts);
var bufferRealSize = buffer.Length;
if(fileSize <= bufferSize)
{
bufferRealSize = fileSize;
}
else if(currentPart == totalParts - 1)
{
bufferRealSize = fileSize - (currentPart*bufferSize);
}
Array.Resize(ref buffer, bufferRealSize);
if (buffer.Length == 0 && previousPart == null)
{
newPart = null;
}
else if (buffer.Length == 0 && previousPart != null)
{
newPart = previousPart;
}
else if (previousPart != null)
{
var newPartLength = previousPart.Length + buffer.Length;
var bufferLength = buffer.Length;
if (newPartLength > fileSize)
{
newPartLength = fileSize;
bufferLength = fileSize - previousPart.Length;
}
newPart = new byte[newPartLength];
Buffer.BlockCopy(previousPart, 0, newPart, 0,
previousPart.Length);
Buffer.BlockCopy(buffer, 0, newPart, previousPart.Length,
bufferLength);
}
else
{
newPart = buffer;
}
if (newPart == null || newPart.Length < fileSize)
{
WaitForFile(socket, fileReceivedCallback, fileSize, bufferSize, newPart, currentPart + 1, totalParts);
return;
}
try
{
socket.EndReceive(asyncResult);
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
return;
}
if (fileReceivedCallback != null)
{
fileReceivedCallback(newPart);
}
}, null);
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
}
}