本文整理汇总了C#中System.Net.Sockets.Socket.EndSend方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.EndSend方法的具体用法?C# Socket.EndSend怎么用?C# Socket.EndSend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.EndSend方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendCommand
protected void SendCommand(Socket socket, string command, CommandSentEventHandler callback, bool closeConnection = false)
{
try
{
Wait();
var byteData = DongleEncoding.Default.GetBytes(command);
socket.BeginSend(byteData, 0, byteData.Length, 0, asyncResult =>
{
int bytesSent;
try
{
bytesSent = socket.EndSend(asyncResult);
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
return;
}
IsSending = false;
if (callback != null)
{
callback(command, bytesSent);
}
if (closeConnection)
{
try
{
socket.Disconnect(false);
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
}
}
}, null);
}
catch (Exception)
{
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
}
}
示例2: SendAsync
/// <summary>
/// 发送信息
/// </summary>
/// <param name="client"></param>
/// <param name="message"></param>
public void SendAsync(Socket client, string message) {
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
try {
client.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, ac => {
try {
int len = client.EndSend(ac);
}
catch (Exception ex) {
ExceptionAction(ex, client);
}
}, null);
}
catch (Exception ex) {
ExceptionAction(ex, client);
}
}
示例3: SendCallback
private void SendCallback(IAsyncResult ar)
{
try
{
handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
}
catch (Exception ex)
{
//弹出相关错误事件
if (OnError != null)
{
OnError(ex.HResult.ToString() + "[SendCallback]", ex.Message);
}
}
}
示例4: OnSend
public void OnSend( IAsyncResult ar )
{
_socket = (Socket)ar.AsyncState;
try
{
int bytesSent = _socket.EndSend(ar);
if (bytesSent > 0)
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error processing receive buffer!");
}
}
示例5: Main
static void Main(string[] args)
{
var nancyApp = StartupNancyApp();
//var workingTitleApp = StartupWorkingTitleApp();
for (;;)
{
var input = Console.ReadLine();
if (input == "exit")
{
nancyApp.Dispose();
//workingTitleApp.Dispose();
return;
}
if (input == "1")
{
var request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080");
try
{
request.GetResponse();
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
}
else if (input == "2")
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect("localhost", 8080);
var blocking = socket.Blocking;
socket.Blocking = false;
//var sr = socket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, ar =>
// {
// socket.EndReceive(ar);
// }, null);
//var optionOutValue = new byte[4];
//var ioControl = socket.IOControl(IOControlCode.NonBlockingIO, new byte[] {1, 0, 0, 0}, optionOutValue);
unsafe
{
var wsabuf = new WSABUF();
uint numberOfBytesRecvd;
var flags = SocketFlags.None;
var result = WSARecv(
socket.Handle, ref wsabuf, 1, out numberOfBytesRecvd, ref flags, null, CallbackThunk1);
var lastError = result == -1 ? Marshal.GetLastWin32Error() : 0;
var overlapped = new Overlapped();
overlapped.AsyncResult = new ARes();
var nativeOverlapped = overlapped.Pack(Iocb, null);
Trace.WriteLine(string.Format("{0}", new IntPtr(nativeOverlapped)));
wsabuf = new WSABUF {buf = Marshal.AllocCoTaskMem(512), len = 512};
var result2 = WSARecv2(
socket.Handle,
ref wsabuf,
1,
out numberOfBytesRecvd,
ref flags,
nativeOverlapped,
IntPtr.Zero);
var lastError2 = result2 == -1 ? Marshal.GetLastWin32Error() : 0;
var data = @"GET / HTTP/1.1
Host: localhost
Connection: close
".ToArraySegment();
SocketError err;
socket.BeginSend(
data.Array,
data.Offset,
data.Count,
SocketFlags.None,
out err,
ar =>
{
socket.EndSend(ar);
socket.Shutdown(SocketShutdown.Send);
},
null);
}
}
else
{
Console.WriteLine("Known input. Enter exit to exit.");
}
}
}
示例6: OnSend
public void OnSend(IAsyncResult ar)
{
_socket = (Socket)ar.AsyncState;
try
{
int bytesSent = _socket.EndSend(ar);
if (bytesSent > 0)
{
}
}
catch (Exception)
{
_textCallback("Error sending data.");
return;
}
}
示例7: sockSendEnd
private void sockSendEnd(IAsyncResult ar)
{
_Sock = (Socket)ar.AsyncState;
try
{
int bytesSent = _Sock.EndSend(ar);
}
catch (Exception e)
{ Console.WriteLine("sndEnd " + e.ToString()); }
}
示例8: Send
protected void Send(Socket socket, string data)
{
var byteData = Encoding.ASCII.GetBytes(data + "<EOF>");
socket.BeginSend(byteData, 0, byteData.Length, 0, ar => socket.EndSend(ar), null);
}
示例9: SendCallback
private void SendCallback(IAsyncResult ar)
{
try
{
handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
}
catch (Exception e)
{
Utils.Logger.getInstance.error(e.ToString());
}
}
示例10: NetworkWrite
private void NetworkWrite(ProcessData Processor, SocketPurpose Purpose, Socket NetworkSocket, byte[] Data, int offset, IAsyncResult ar)
{
try
{
int length = NetworkSocket.EndSend(ar);
if (length + offset < Data.Length)
{
NetworkSocket.BeginSend(Data, length, Data.Length - (length + offset), SocketFlags.None,
delegate(IAsyncResult AsR) { NetworkWrite(Processor, Purpose, NetworkSocket, Data, length + offset, AsR); },
null);
}
else
{
NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
delegate(IAsyncResult AsR) { NetworkReceive(Purpose, NetworkSocket, AsR); },
null);
}
}
catch (SocketException e)
{
OnSocketException(Purpose, NetworkSocket, e);
}
catch (ObjectDisposedException)
{
OnObjectDisposedException(Purpose, NetworkSocket);
}
}
示例11: Handle
/// <summary>
/// Handles the auth request packet.
/// </summary>
/// <param name="client">The auth client.</param>
/// <param name="Packet">The packet.</param>
public static void Handle(Client.AuthClient client, DataPacket Packet)
{
using (var auth = new AuthRequestPacket(Packet))
{
Enums.AccountStatus status = Database.ServerDatabase.Authenticate(client, auth.Account, auth.Password);
client.EntityUID = (uint)ProjectX_V3_Lib.ThreadSafe.RandomGenerator.Generator.Next(1000000, 699999999);
if (status == Enums.AccountStatus.Ready)
{
try
{
Database.ServerDatabase.UpdateAuthentication(client);
Socket quicksock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
quicksock.Connect(new IPEndPoint(IPAddress.Parse(Program.Config.ReadString("GameIP")), Program.Config.ReadInt32("GameAuthPort")));
using (DataPacket packet = new DataPacket(44, 9001))
{
packet.WriteString(Program.Config.ReadString("ServerPassword"), 4);
packet.WriteString(client.Account, 20);
packet.WriteInt32(client.DatabaseUID, 36);
packet.WriteUInt32(client.EntityUID, 40);
quicksock.BeginSend(packet.Copy(), 0, 44, SocketFlags.None,
new AsyncCallback((ia) =>
{
int send = quicksock.EndSend(ia);
if (send != 44)
{
status = Enums.AccountStatus.Datebase_Error;
client.EntityUID = 0;
}
Console.WriteLine("Database Notified: [Account: {0}] [DUID: {1}] [EUID: {2}]", client.Account, client.DatabaseUID, client.EntityUID);
}), null);
}
System.Threading.Thread.Sleep(2000);
}
catch
{
status = Enums.AccountStatus.Datebase_Error;
}
}
using (var resp = new AuthResponsePacket())
{
if (status == Enums.AccountStatus.Ready)
{
Console.WriteLine("Incoming login. [Account: {0}] [Password: {1}]", client.Account, client.Password);
resp.EntityUID = client.EntityUID;
resp.Port = Program.Config.ReadUInt32("GamePort");
resp.IPAddress = Program.Config.ReadString("GameIP");
}
else
{
resp.EntityUID = 0;
}
resp.AccountStatus = status;
client.Send(resp);
}
System.Threading.Thread.Sleep(5000);
client.NetworkClient.Disconnect("TIME_OUT");
}
}
示例12: Connect
private void Connect(string serverIp, string name)
{
try
{
_chatName = name;
// Initialize socket.
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Initialize server IP.
var serverIP = IPAddress.Parse(serverIp);
// Initialize the IPEndPoint for the server and use port SERVER_PORT.
var server = new IPEndPoint(serverIP, ServerInfo.PORT);
// Initialize the EndPoint for the server.
_serverEndPoint = server as EndPoint;
var state = new StateObject()
{
Data = new ChatPacket()
{
ChatName = _chatName,
ChatMessage = null,
ChatDataIdentifier = DataIdentifier.LogIn
}.Serialize()
};
// Send data to server.
_clientSocket.BeginSendTo(state.Data, 0, state.Data.Length, SocketFlags.None, _serverEndPoint, ar => _clientSocket.EndSend(ar), state);
// Initialize data stream.
state = new StateObject();
// Begin listening for broadcasts from the server.
_clientSocket.BeginReceiveFrom(state.Data, 0, state.Data.Length, SocketFlags.None, ref _serverEndPoint, EndReceive, state);
}
catch (Exception ex)
{
Logger.WriteLine("Connection error!");
Logger.WriteLine(ex.Message);
}
}
示例13: SendFile
protected void SendFile(Socket socket, FileSentEventHandler callback, byte[] fileData, int offset = 0, int bufferSize = DefaultBufferSize)
{
//Wait();
var sendingLength = bufferSize;
if (offset + bufferSize > fileData.Length)
{
sendingLength = fileData.Length - offset;
}
socket.SendTimeout = 1000000;
socket.BeginSend(fileData, offset, sendingLength, SocketFlags.None, asyncResult =>
{
try
{
socket.EndSend(asyncResult);
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
if (OnSocketDisconnected != null)
{
OnSocketDisconnected(socket);
}
return;
}
if (offset + sendingLength < fileData.Length)
{
SendFile(socket, callback, fileData, offset + bufferSize, bufferSize);
}
IsSending = false;
if (callback != null)
{
callback();
}
}, null);
}
示例14: OnSend
private void OnSend(IAsyncResult ar)
{
try
{
_clientSocket = (Socket)ar.AsyncState;
_clientSocket.EndSend(ar);
}
catch (ObjectDisposedException oex)
{
InvokeConnectionServerEvent(new ConnectionServerEventArgs(ConnectionServerEventType.ERROR_OCCURED, "Error during connection (OnSend, Disposed): " + oex.Message));
}
catch (Exception ex)
{
InvokeConnectionServerEvent(new ConnectionServerEventArgs(ConnectionServerEventType.ERROR_OCCURED, "Server error | [OnSend]: " + ex.Message));
ResetSocket(false);
}
}
示例15: UdpClient
void IProxy.LaunchProxy()
{
if (_alreadyCalledProxyMethod)
{
return;
}
_alreadyCalledProxyMethod = true;
try
{
UdpClient client = new UdpClient(_src);
Socket server = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
// ---
AsyncCallback clientCallback = null;
AsyncCallback serverCallback = null;
// TODO: Only done once ... even so, put his in assync! :D
server.Connect(_target);
serverCallback = delegate(IAsyncResult res)
{
SocketError err = default(SocketError);
int bytes = server.EndSend(res, out err);
// Check if all was sent ...
if (err == SocketError.Success)
{
Trace.WriteLine(string.Format("Sent {0} bytes to server.", bytes));
}
else
{
Trace.WriteLine(string.Format("Error {0} on sending", err));
}
};
clientCallback = delegate(IAsyncResult res)
{
// Reattach listener asap
client.BeginReceive(clientCallback, client);
byte[] datagram = client.EndReceive(res, ref _src);
Trace.WriteLine(string.Format("Received {0} bytes from client.", datagram.Length));
// Send to target
Trace.WriteLine(string.Format("About to send {0} bytes to server", datagram.Length));
server.BeginSend(
datagram, 0, datagram.Length,
SocketFlags.None, serverCallback, server);
// --
};
IAsyncResult result = client.BeginReceive(clientCallback, client);
}
catch (Exception e)
{
throw e;
// TODO: Better exception message ...
//Trace.WriteLine("Exception at UdpProxy: " + e.Message);
}
}