public void BeginConnectDest(EndPoint remoteEP, AsyncCallback callback, object state) { var ep = remoteEP as IPEndPoint; if (ep == null) { throw new Exception(I18N.GetString("Proxy request faild")); } byte[] request = null; byte atyp = 0; switch (ep.AddressFamily) { case AddressFamily.InterNetwork: request = new byte[4 + 4 + 2]; atyp = 1; break; case AddressFamily.InterNetworkV6: request = new byte[4 + 16 + 2]; atyp = 4; break; } if (request == null) { throw new Exception(I18N.GetString("Proxy request faild")); } // 构造request包 var addr = ep.Address.GetAddressBytes(); request[0] = 5; request[1] = 1; request[2] = 0; request[3] = atyp; Array.Copy(addr, 0, request, 4, request.Length - 4 - 2); request[request.Length - 2] = (byte)((ep.Port >> 8) & 0xff); request[request.Length - 1] = (byte)(ep.Port & 0xff); var st = new Socks5State(); st.Callback = callback; st.AsyncState = state; DestEndPoint = remoteEP; _remote?.BeginSend(request, 0, request.Length, 0, Socks5RequestSendCallback, st); }
public void SendCommand(MessageType type) { SingleCommandMessage msg = new SingleCommandMessage(type); byte[] data = msg.ToBytes(); tcpSocket?.BeginSend(data, 0, data.Length, 0, SendCallback, null); }
public int Write(MemoryStream buffer) { while (_channel == null && _retries < DefaultRetries) { PreparedChannel(); } var totalBytesWritten = 0; if (_channel == null || !_isConnected.Get()) { return(totalBytesWritten); } try { while (buffer.HasRemaining()) { var bytes = new byte[buffer.Length]; buffer.Read(bytes, 0, bytes.Length); totalBytesWritten += bytes.Length; _logger.Debug($"{this}: Sending bytes [{bytes.Length}]"); _channel?.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendCallback, _channel); } } catch (Exception e) { _logger.Error($"{this}: Write to channel failed because: {e.Message}", e); Close(); } return(totalBytesWritten); }
private void HandshakeReceive() { if (_closed) { return; } try { int bytesRead = _firstPacketLength; if (bytesRead > 1) { byte[] response = { 5, 0 }; if (_firstPacket[0] != 5) { // reject socks 4 response = new byte[] { 0, 91 }; Logging.Error("socks 5 protocol error"); } connection?.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(HandshakeSendCallback), null); } else { Close(); } } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
/// <inheritdoc/> public virtual void Send(byte[] data) { if (IsConnected) { Logger.LogDebug("Sending: {Length} bytes - To: {RemoteEndpoint}", data.Length, Socket?.RemoteEndPoint); _ = Socket?.BeginSend(data, 0, data.Length, 0, SendCallback, Socket); } }
public static void Send(Socket client, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); }
internal SocketConnection(URIResolver server, SocketRemote client, Socket socket) : base(server, client) { _socket = socket; setActor(new SocketActor(this)); Buff buff = Buff.getOrCreate(); int position = buff.position(); startWrite(buff); buff.limit(buff.position()); buff.position(position); if (Debug.ENABLED) buff.@lock(buff.limit()); _socket.BeginSend(buff.getByteBuffer().array(), buff.position(), buff.remaining(), SocketFlags.None, Connected, buff); BeginReceive(); }
public void Send(byte[] value) { if (value == null || value.Length == 0) { throw new ArgumentNullException(nameof(value)); } if (_socket != null && _socket.Connected) { try { _socket?.BeginSend(value, 0, value.Length, SocketFlags.None, new AsyncCallback(SendCallback), null); } catch (Exception ex) { if (_showFail) { Debug.Fail(ex.Message, ex.StackTrace); } Disconnect(); } } }
public void Send(Socket client, byte[] byteData) { client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); }
private static void Send( Socket client, String data ) { byte[] byteData = Encoding.ASCII.GetBytes(data); client.BeginSend ( byteData, 0, byteData.Length, 0, new AsyncCallback ( ClientSendCallback ), client ); }
//Sends the message and uses SendCallback() private void Send(Socket client, String data) { try { byte[] byteData = Encoding.ASCII.GetBytes(data); // Convert the string data to byte data using ASCII encoding. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); // Begin sending } catch (Exception ex) { Console.WriteLine(ex.ToString()); log.Debug(ex.ToString()); } }
private static void ReceiveCallback(IAsyncResult AR) { Socket socket = (Socket)AR.AsyncState; int received = socket.EndReceive(AR); byte[] dataBuf = new byte[received]; Array.Copy(_buffer, dataBuf, received); string text = Encoding.ASCII.GetString(dataBuf); Console.WriteLine("Text received: " + text); string response = string.Empty; if (text.ToLower() == "lock screen") { response = "Your Computer Is Locked"; byte[] data = Encoding.ASCII.GetBytes(response); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); LockWorkStation(); } else if (text.ToLower() == "shut down") { response = "Your Computer Is Shutted Down"; byte[] data = Encoding.ASCII.GetBytes(response); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); System.Diagnostics.Process.Start(@"C:\WINDOWS\system32\Shutdown", "-s -f -t 00"); } else if (text.ToLower() == "start spy") { if (capture != null) { capture.Dispose(); } if (streamerThread != null && streamerThread.IsAlive) { streamerThread.Abort(); sending_socket.Close(); } if (screenStreamerThread != null && screenStreamerThread.IsAlive) { screenStreamerThread.Abort(); screen_socket.Close(); } response = "Live Streaming is Starting"; byte[] data = Encoding.ASCII.GetBytes(response); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); VideoStream(); WindowStream(); } else if (text.ToLower() == "stop stream") { if (capture != null) { capture.Dispose(); } if (streamerThread != null && streamerThread.IsAlive) { streamerThread.Abort(); sending_socket.Close(); } if (screenStreamerThread != null && screenStreamerThread.IsAlive) { screenStreamerThread.Abort(); screen_socket.Close(); } } else if (text.ToLower() == "video stream") { response = "Screen Streaming is Starting"; byte[] data = Encoding.ASCII.GetBytes(response); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); VideoStream(); } else if (text.ToLower() == "screen stream") { response = "Screen Streaming is Starting"; byte[] data = Encoding.ASCII.GetBytes(response); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); WindowStream(); } }
/// <summary> /// 接收客户端发送的数据,进行socks5版本及认证方式的协商。然后向客户端应答 /// </summary> private void HandshakeReceive() { if (closed) { return; } try { /* * 建立与 SOCKS5 服务器的TCP连接后,客户端需要先发送请求来协商版本及认证方式。 +----+----------+----------+ |VER | NMETHODS | METHODS | +----+----------+----------+ | 1 | 1 | 1 to 255 | +----+----------+----------+ | VER 是 SOCKS 版本,这里应该是 0x05; | NMETHODS 是 METHODS 部分的长度; | METHODS 是客户端支持的认证方式列表,每个方法占1字节。当前的定义是: | 0x00 不需要认证 | 0x01 GSSAPI | 0x02 用户名、密码认证 | 0x03 - 0x7F 由IANA分配(保留) | 0x80 - 0xFE 为私人方法保留 | 0xFF 无可接受的方法 */ int bytesRead = _firstPacketLength; /* * 应答数据包,与客户端协商版本与认证方式 +----+--------+ |VER | METHOD | +----+--------+ | 1 | 1 | +----+--------+ | VER 是 SOCKS 版本,这里应该是 0x05; | METHOD 是服务端选中的方法。如果返回 0xFF 表示没有一个认证方法被选中,客户端需要关闭连接。 */ if (bytesRead > 1) { byte[] response = { 5, 0 }; // 表示不需要认证 if (_firstPacket[0] != 5) { // reject socks 4 response = new byte[] { 0, 91 }; //91,请求被拒绝或失败,socket4的应答方式,详见 https://zh.wikipedia.org/wiki/SOCKS Console.WriteLine("socks 5 protocol error"); } // 向客户端应答 Logging.Debug($"======Send Local Port, size:" + response.Length); connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(HandshakeSendCallback), null); } else { this.Close(); } } catch (Exception e) { Logging.LogUsefulException(e); this.Close(); } }
public void StartClient() { IPAddress ip = IPAddress.Parse("192.168.56.1"); int port = 8080; IPEndPoint ipEnd = new IPEndPoint(ip, port); client.Connect(ipEnd); Socket handler = client.Client; string path; Console.Write("Would you like to send a file or a directory: "); if (Console.ReadLine().ToLower() == "file") { Console.Write("Choose a File to Send: "); path = Console.ReadLine(); while (!File.Exists(path)) { Console.Write("ERROR: File Entered Does not Exist on Selected Disk\nChoose a File to Send: "); path = Console.ReadLine(); } FileStream file = File.OpenRead(path); byte[] b = new byte[2048]; file.Read(b, 0, b.Length); string fileSend = Encoding.UTF8.GetString(b) + "$" + file.Name + "%%2"; b = Encoding.UTF8.GetBytes(fileSend); Console.Write("Sending File: " + file.Name + "... "); handler.BeginSend(b, 0, b.Length, 0, SendCallBack, new State(handler, b)); } else { Console.Write("Choose a Directory to Send: "); path = Console.ReadLine(); while (!Directory.Exists(path)) { Console.Write("ERROR: Directory Entered Does not Exist on Selected Disk\nChoose a Directory to Send: "); path = Console.ReadLine(); } DirectoryInfo directory = new DirectoryInfo(path); IEnumerator <FileInfo> files = directory.EnumerateFiles().GetEnumerator(); Console.WriteLine(directory.GetFiles().Length); while (files.MoveNext()) { mre.Reset(); FileInfo file = files.Current; Console.Write("Sending File: " + file.Name + "... "); byte[] b = new byte[file.Length]; file.OpenRead().Read(b, 0, b.Length); string fileSend = Encoding.UTF8.GetString(b) + "$" + file.Name + "%%2"; b = Encoding.UTF8.GetBytes(fileSend); handler.BeginSend(b, 0, b.Length, 0, SendCallBack, new State(handler, b)); mre.WaitOne(); } } handler.BeginDisconnect(false, DisconnectCallBack, handler); }
private static void Send(Socket handler, String data) { byte[] byteData = Encoding.ASCII.GetBytes(data); handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); }
private static void Send(Socket handler, String data) { try { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } catch (Exception e) { connected = false; Debug.Log(e.ToString()); } }
// TODO: StateObject is hard-coded to max out at 1024 bytes. Please define somewhere consistent. // TODO: Add RTCs for data size. Should not exceed max or be less than zero. // TODO: Genericize this to work with other types of data public void Send(Socket handler, byte[] data) { try { handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), handler); } catch (SocketException ex) { Debug.LogWarning(ex.Message); players[handler].isActive = false; DropConnection(handler); events.Add(new SocketEvent(new SocketEventArgs(SocketEventArgs.SocketEventType.DROP, players[handler]), null)); } }
private static void Send(Socket handler, String data) { // Convert the string data to byte data using ASCII encoding. Response response = new Response(); response.Success = true; response.Data = data + "Handled by MAIN SEND"; response.SetImage(new System.Drawing.Bitmap("C:/Work/Projects/Tests/ServerClient/TestServer/TestServer/TestImages/GMan.png")); string s = XMLHelper<Response>.SerializeStringToXML(response); byte[] byteData = Encoding.ASCII.GetBytes(s); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); }
private static void Send(Socket handler, byte[] data, int length) { var dataClone = data.Clone(); handler.BeginSend((byte[])dataClone, 0, length, 0, new AsyncCallback(SendCallback), handler); }
private static void AnotherSend(Socket handler, String data) { // Convert the string data to byte data using ASCII encoding. Response response = new Response(); response.Success = true; response.Data = data + "Handled by ANOTHER SEND"; string s = XMLHelper<Response>.SerializeStringToXML(response); byte[] byteData = Encoding.ASCII.GetBytes(s); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); }
private void Send(Socket socket, byte[] data) { LogsSystem.Instance.Print(string.Format("TCP 发送数据({0}):{1}", data.Length, encoding.GetString(data))); socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), socket); }
private void Send(Socket client, string data) { byte[] byteData = Encoding.UTF8.GetBytes(data); client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(SendCallback), client); }
private static void SendBinary(Socket client, byte[] data) { byte[] byteData = data; client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(_socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state)); }
private static void SendData(string data, Socket socket) { byte[] DataBytes = Encoding.ASCII.GetBytes(data); socket.BeginSend(DataBytes, 0, DataBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); }
void Send(string str) { byte[] msg = Encoding.UTF8.GetBytes(str); client.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(SendData), client); //开始发送 }
public void Send(GyroQuaternion gyroQuaternion) { byte[] data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(gyroQuaternion)); udpSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), udpSocket); sendDone.WaitOne(); }
/// <summary> /// 发送数据包 /// </summary> /// <param name="sock"></param> /// <param name="data"></param> public void SendData(Socket sock, byte[] data) { sock.BeginSend(data, 0, data.Length, SocketFlags.None, AsynCallBack, sock); }
public void SendName(Socket client, string name) { byte[] nameData = Encoding.UTF8.GetBytes(name); client.BeginSend(nameData, 0, nameData.Length, 0, new AsyncCallback(SendCallback), client); }
private static void Send(Socket handler, String data) { try { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } catch (Exception e) { Debug.Log("[ROTATION_SERVER] Network Exception, trying to reconnect. " + e); //server.closeConnection(); } }
private static void Send(Socket client, string data) { byte[] byteData = Encoding.ASCII.GetBytes(data); client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); }
public void Send(Socket socket, byte[] data, int length) { try { socket.BeginSend(data, 0, length, 0, new AsyncCallback(SendCallback), socket); } catch (Exception e) { Debug.Log("<color=green>S: Send </color>" + e.ToString()); } }
/// <summary> /// 往客户端发送消息 /// </summary> /// <param name="buffer"></param> public void Send(byte[] buffer) { mClicentSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallBack, mClicentSocket); }
private static void SendServer(Socket handler, string data) { byte[] byteData = Encoding.Unicode.GetBytes(data); handler.BeginSend(byteData, 0, byteData.Length, 0, SendCallbackServer, handler); }
private static void ReceiveCallback(IAsyncResult AR) { Socket socket = (Socket)AR.AsyncState; int received = socket.EndReceive(AR); byte[] dataBuf = new byte[received]; Array.Copy(_buffer, dataBuf, received); string text = Encoding.ASCII.GetString(dataBuf); // if (text != "") { // dynamic jsondata = JsonConvert.DeserializeObject(text);// jsondata...barcodeno if (jsondata.islem == 0) { Console.WriteLine("İşlem No : " + jsondata.islem); Console.WriteLine("Barcode no : " + jsondata.barcodeno); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else if (jsondata.islem == 1) //Barcode // Önemli!! //Bilgiler geldiğinde önce barcode no ile database den o barcode a ait bilgileri { //al(açıklama,kod,fiyat) gibi sonrasında bu bilgiler ile birlikte database e ekle. //Geriye "barcodeno"-"fiyat"-"miktar"(eklenmiş olan miktarı) gönder ve telefonda da ayrı db tut ekranda göster //eğer silinmesi istenirse işlem 0 ile barcode ve miktar gönder. gelen miktar kadar barcode numarasına göre db den kaldır Console.WriteLine("İşlem No : " + jsondata.islem); string barcodeno = jsondata.barcodeno; int miktar = jsondata.miktar; string sayimfisi = jsondata.sayimfisi, depo = jsondata.depo, tarih = jsondata.tarih, sg = jsondata.sayimgorevlisi, reyon = jsondata.reyon, pn = jsondata.personelnotu; DateTime time = DateTime.Now; try { //@"Data Source=(DESKTOP-AM0TU5O)\(SQLEXPRESS);Initial Catalog=(faturalar);Integrated Security=True;" SqlConnection sqlCon = new SqlConnection(@"Server=localhost\SQLEXPRESS;Database=faturalar;Trusted_Connection=True;"); sqlCon.Open(); Console.WriteLine("Connection Open ! "); /* SqlCommand sqlCommand = new SqlCommand("INSERT INTO fatura (barcodeno,aciklama,[kod(stok)],miktar,sayimfisi,depo,tarih,sayimgorevlisi,reyon,personelnotu)" + * "Values ("+jsondata.barcodeno+", 'açıklama','kodstok',"+jsondata.miktar+","+jsondata.sayimfisi+ ","+jsondata.depo+","+jsondata.tarih+","+jsondata.sayimgorevlisi+ ","+jsondata.reyon+","+jsondata.personelnotu+ ")", sqlCon);*/ /* SqlCommand sqlCommand = new SqlCommand("INSERT INTO fatura (barcodeno,aciklama,[kod(stok)],miktar,sayimfisi,depo,tarih,sayimgorevlisi,reyon,personelnotu)" + * "Values (" + barcodeno + ", 'açıklama','kodstok'," + miktar + "," + sayimfisi+ "," + depo + "," + tarih + "," + sg + "," + reyon + "," + pn + ")", sqlCon);*/ SqlCommand sqlCommand = new SqlCommand("INSERT INTO fatura (barcodeno,aciklama,[kod(stok)],miktar,sayimfisi,depo,tarih,sayimgorevlisi,reyon,personelnotu)" + "Values (" + barcodeno + ", 'Açıklama','Kod(STOK)'," + miktar + ",'" + sayimfisi + "','" + depo + "','" + time.ToString(tarih) + "','" + sg + "','" + reyon + "','" + pn + "')", sqlCon); sqlCommand.ExecuteNonQuery(); // insert into tablename (barcodeno) values "2123134566"); sqlCon.Close(); } catch (Exception ex) { Console.WriteLine("Eklenmezse geri bildirim gönder! "); } Console.ReadKey(); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else if (jsondata.islem == 2)//Açıklama { Console.WriteLine("İşlem No : " + jsondata.islem); string aciklama = jsondata.barcodeno; int miktar = jsondata.miktar; string sayimfisi = jsondata.sayimfisi, depo = jsondata.depo, tarih = jsondata.tarih, sg = jsondata.sayimgorevlisi, reyon = jsondata.reyon, pn = jsondata.personelnotu; DateTime time = DateTime.Now; try { //@"Data Source=(DESKTOP-AM0TU5O)\(SQLEXPRESS);Initial Catalog=(faturalar);Integrated Security=True;" SqlConnection sqlCon = new SqlConnection(@"Server=localhost\SQLEXPRESS;Database=faturalar;Trusted_Connection=True;"); sqlCon.Open(); Console.WriteLine("Connection Open ! "); SqlCommand sqlCommand = new SqlCommand("INSERT INTO fatura (barcodeno,aciklama,[kod(stok)],miktar,sayimfisi,depo,tarih,sayimgorevlisi,reyon,personelnotu)" + "Values ( 'Barkodno' , '" + aciklama + "','Kod(STOK)'," + miktar + ",'" + sayimfisi + "','" + depo + "','" + time.ToString(tarih) + "','" + sg + "','" + reyon + "','" + pn + "')", sqlCon); sqlCommand.ExecuteNonQuery(); sqlCon.Close(); } catch (Exception ex) { Console.WriteLine("Eklenmezse geri bildirim gönder! "); } Console.ReadKey(); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else if (jsondata.islem == 3)//Kod(Stok) { Console.WriteLine("İşlem No : " + jsondata.islem); string kodstok = jsondata.barcodeno; int miktar = jsondata.miktar; string sayimfisi = jsondata.sayimfisi, depo = jsondata.depo, tarih = jsondata.tarih, sg = jsondata.sayimgorevlisi, reyon = jsondata.reyon, pn = jsondata.personelnotu; DateTime time = DateTime.Now; try { //@"Data Source=(DESKTOP-AM0TU5O)\(SQLEXPRESS);Initial Catalog=(faturalar);Integrated Security=True;" SqlConnection sqlCon = new SqlConnection(@"Server=localhost\SQLEXPRESS;Database=faturalar;Trusted_Connection=True;"); sqlCon.Open(); Console.WriteLine("Connection Open ! "); SqlCommand sqlCommand = new SqlCommand("INSERT INTO fatura (barcodeno,aciklama,[kod(stok)],miktar,sayimfisi,depo,tarih,sayimgorevlisi,reyon,personelnotu)" + "Values ( 'Barkodno' , 'Açıklama','" + kodstok + "'," + miktar + ",'" + sayimfisi + "','" + depo + "','" + time.ToString(tarih) + "','" + sg + "','" + reyon + "','" + pn + "')", sqlCon); sqlCommand.ExecuteNonQuery(); sqlCon.Close(); } catch (Exception ex) { Console.WriteLine("Eklenmezse geri bildirim gönder! "); } Console.ReadKey(); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else if (jsondata.islem == 4) { Console.WriteLine("İşlem No : " + jsondata.islem); Console.WriteLine("Depo : " + jsondata.depo); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else if (jsondata.islem == 5) { Console.WriteLine("İşlem No : " + jsondata.islem); Console.WriteLine("Sayım Görevlisi : " + jsondata.sayimgorevlisi); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } else { Console.WriteLine("İşlem No : " + jsondata.islem); Console.WriteLine("Reyon : " + jsondata.reyon); byte[] data = Encoding.ASCII.GetBytes(text); socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } } socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket); }
public virtual void Send(Packet p) { if (m_Socket == null || m_BlockAllPackets) { p.OnSend(); return; } PacketSendProfile prof = PacketSendProfile.Acquire(p.GetType()); int length; byte[] buffer = p.Compile(m_CompressionEnabled, out length); if (buffer != null) { if (buffer.Length <= 0 || length <= 0) { p.OnSend(); return; } if (prof != null) { prof.Start(); } if (m_Encoder != null) { m_Encoder.EncodeOutgoingPacket(this, ref buffer, ref length); } try { SendQueue.Gram gram; lock ( m_SendQueue ) { gram = m_SendQueue.Enqueue(buffer, length); } if (gram != null) { try { m_Socket.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, m_Socket); } catch (Exception ex) { TraceException(ex); Dispose(false); } } } catch (CapacityExceededException) { Console.WriteLine("Client: {0}: Too much data pending, disconnecting...", this); Dispose(false); } p.OnSend(); if (prof != null) { prof.Finish(length); } } else { Console.WriteLine("Client: {0}: null buffer send, disconnecting...", this); using (StreamWriter op = new StreamWriter("null_send.log", true)) { op.WriteLine("{0} Client: {1}: null buffer send, disconnecting...", DateTime.Now, this); op.WriteLine(new System.Diagnostics.StackTrace()); } Dispose(); } }
public override Task <int> SendAsync(Socket s, ArraySegment <byte> buffer) => Task.Factory.FromAsync((callback, state) => s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state), s.EndSend, null);
public static async Task <int> SendAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags) { return(await Task <int> .Factory.FromAsync((callback, state) => socket.BeginSend(buffer, offset, size, flags, callback, state), ias => socket.EndSend(ias), null)); }
private void SendBytesToSocket(Socket?s, byte[] data) => _ = s?.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendData), s);
internal void ManageHandshake(IAsyncResult status) { TrySocketAction(r => { string header = "Sec-WebSocket-Version:"; int HandshakeLength = (int)status.AsyncState; byte[] last8Bytes = new byte[8]; var decoder = new UTF8Encoding(); String rawClientHandshake = decoder.GetString(ReceivedDataBuffer, 0, HandshakeLength); Array.Copy(ReceivedDataBuffer, HandshakeLength - 8, last8Bytes, 0, 8); //现在使用的是比较新的Websocket协议 if (rawClientHandshake.IndexOf(header) != -1) { this.IsDataMasked = true; string[] rawClientHandshakeLines = rawClientHandshake.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); string acceptKey = ""; foreach (string Line in rawClientHandshakeLines) { if (Line.Contains("Sec-WebSocket-Key:")) { acceptKey = ComputeWebSocketHandshakeSecurityHash09(Line.Substring(Line.IndexOf(":") + 2)); } if (Line.Contains("RouteKey=")) { SetBroadCastRouteKey(Line); } } new_Handshake = string.Format(new_Handshake, acceptKey); byte[] newHandshakeText = Encoding.UTF8.GetBytes(new_Handshake); ConnectionSocket.BeginSend(newHandshakeText, 0, newHandshakeText.Length, 0, HandshakeFinished, null); return; } string ClientHandshake = decoder.GetString(ReceivedDataBuffer, 0, HandshakeLength - 8); string[] ClientHandshakeLines = ClientHandshake.Split(new string[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries); // Welcome the new client foreach (string Line in ClientHandshakeLines) { if (Line.Contains("RouteKey=")) { SetBroadCastRouteKey(Line); } if (Line.Contains("Sec-WebSocket-Key1:")) { BuildServerPartialKey(1, Line.Substring(Line.IndexOf(":") + 2)); } if (Line.Contains("Sec-WebSocket-Key2:")) { BuildServerPartialKey(2, Line.Substring(Line.IndexOf(":") + 2)); } if (Line.Contains("Origin:")) { try { handshake = string.Format(handshake, Line.Substring(Line.IndexOf(":") + 2)); } catch { handshake = string.Format(handshake, "null"); } } } // Build the response for the client byte[] HandshakeText = Encoding.UTF8.GetBytes(handshake); byte[] serverHandshakeResponse = new byte[HandshakeText.Length + 16]; byte[] serverKey = BuildServerFullKey(last8Bytes); Array.Copy(HandshakeText, serverHandshakeResponse, HandshakeText.Length); Array.Copy(serverKey, 0, serverHandshakeResponse, HandshakeText.Length, 16); ConnectionSocket.BeginSend(serverHandshakeResponse, 0, HandshakeText.Length + 16, 0, HandshakeFinished, null); }); }
/// <summary> /// 向单个连接发送消息 /// </summary> /// <param name="b"></param> /// <param name="s"></param> public void Send(string b, Socket s) { byte[] a = Encoding.UTF8.GetBytes(b); s.BeginSend(a, 0, a.Length, 0, new AsyncCallback(sentback), s); }
private IAsyncResult _socketBeginSend(byte[] buffer) => _socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(_EndSendCallback), buffer);
private void Send(byte[] data) { m_Socket?.BeginSend(data, 0, data.Length, SocketFlags.None, SendComplete, null); }
public void Send(Packet p) { if (m_Socket == null) { return; } PacketProfile prof = PacketProfile.GetOutgoingProfile((byte)p.PacketID); DateTime start = (prof == null ? DateTime.MinValue : DateTime.Now); byte[] buffer = p.Compile(m_CompressionEnabled); if (buffer != null) { if (buffer.Length <= 0) { return; } int length = buffer.Length; if (m_Encoder != null) { m_Encoder.EncodeOutgoingPacket(this, ref buffer, ref length); } bool shouldBegin = false; lock (m_SendQueue) shouldBegin = (m_SendQueue.Enqueue(buffer, length)); if (m_Connecting) { shouldBegin = false; } if (shouldBegin) { int sendLength = 0; byte[] sendBuffer = m_SendQueue.Peek(ref sendLength); try { m_Socket.BeginSend(sendBuffer, 0, sendLength, SocketFlags.None, m_OnSend, null); m_Sending = true; //Console.WriteLine( "Send: {0}: Begin send of {1} bytes", this, sendLength ); } catch // ( Exception ex ) { //Console.WriteLine(ex); Dispose(false); } } if (prof != null) { prof.Record(length, DateTime.Now - start); } } else { Dispose(); } }
public void BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state) { _remote?.BeginSend(buffer, offset, size, socketFlags, callback, state); }
public static void SendMsgToClient(Socket client, string msg) { byte[] bt = ServerHelper.EncodeMsg(msg); client.BeginSend(bt, 0, bt.Length, SocketFlags.None, new AsyncCallback(SendTarget), client); }
private static void Send(Socket handler, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); }
private static void Send(Socket client, string data) { // 0 : DEFAULT // 1 : ERROR // 2 : INFO // 3 : DEBUG // 4 : TIME byte[] byteData = Encoding.ASCII.GetBytes(data); client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); }