public BeginReceiveFrom ( byte buffer, int offset, int size, SocketFlags socketFlags, |
||
buffer | byte | |
offset | int | |
size | int | |
socketFlags | SocketFlags | |
remoteEP | ||
callback | AsyncCallback | |
state | object | |
return | IAsyncResult |
//metodo eseguito al click sul pulsante connetti private void btnConnect_Click(object sender, EventArgs e) { //vengono memorizzati il nome utente e //viene aggiornata la casella di testo _userName = txtUserName.Text.Trim(); _setText = SetText; //viene creato e riempito un pacchetto di richiesta di join alla chat Packet sendData = new Packet(); sendData.DataIdentifier = DataTypeIdentifier.Login; sendData.UserName = _userName; //viene creato un Socket UDP _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //viene creato un oggetto contenente l'indirizzo IP e la porta del server IPAddress serverIP = IPAddress.Parse(txtServerAddress.Text); int serverPort = int.Parse(txtServerPort.Text); _epServer = new IPEndPoint(serverIP, serverPort); //il pacchetto creato viene convertito in un'array di byte _dataStream = sendData.ToByteArray(); //il pacchetto creato viene spedito al server _clientSocket.BeginSendTo(_dataStream, 0, _dataStream.Length, SocketFlags.None, _epServer, SendData, null); //tutti gli oggetti vengono sempre passati per referenza //il client si mette ora in ascolto dei messaggi provenienti dal server EndPoint ep = _epServer; _dataStream = new byte[Properties.Settings.Default.MAX_PACKET_LENGTH]; _clientSocket.BeginReceiveFrom(_dataStream, 0, _dataStream.Length, SocketFlags.None, ref ep, ReceiveData, null); }
/// <summary> /// Create a new instance of the server context type. /// </summary> private void CreateServerContext() { try { // Create a new instance of the server context type UdpSimpleContext context = new UdpSimpleContext(_specificAddressFamily); context.Socket = _socket; context.ReceiveSocketFlags = _receiveSocketFlags; context.SendSocketFlags = _sendSocketFlags; context.ReadBufferSize = READ_BUFFER_SIZE; context.WriteBufferSize = WRITE_BUFFER_SIZE; context.Server = this; // Create a new client data receive handler, this event // handles commands from the current client. context.OnCommandSend += new UdpSimpleContextHandler(SocketServer_OnCommandSend); // Increment the count. IncrementCount(); // Lock the socket receive process. lock (LockingSocket) { // Start receiving data from the client. _socket.BeginReceiveFrom(context._readBuffer, 0, context.ReadBufferSize, context.ReceiveSocketFlags, ref context.RemoteClient, new AsyncCallback(context.DataReceiver), context); } } catch (Exception ex) { SetLastError(ex); } }
private void EndReceiveFromCallback(System.IAsyncResult iar) { State state = iar.AsyncState as State; System.Net.Sockets.Socket socket = state.Socket; try { int byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP); var readbuf = new byte[state.Buffer.Length]; byte[] datasize = new byte[4]; System.Array.Copy(state.Buffer, datasize, datasize.Length); int size = BitConverter.ToInt32(datasize, 0); if (size > 0) { socket.BeginReceiveFrom(state.Buffer, 0, size, System.Net.Sockets.SocketFlags.None, ref state.RemoteEP, new System.AsyncCallback(this.EndReceiveFromCallback), state); } else { System.Array.Copy(state.Buffer, readbuf, readbuf.Length); this.UnPackage(readbuf); } } catch (Exception e) { LogerHelper.Loger.Error(e); this.RecOpen(); } }
public void StartListening() { EndPoint localEp = ( EndPoint )_iep; Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); try { listener.Bind( localEp ); while ( true ) { allDone.Reset(); StateObject so = new StateObject(); so.workSocket = listener; Console.WriteLine( "Waiting for a connection..." ); IAsyncResult result = listener.BeginReceiveFrom( so.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None, ref localEp, new AsyncCallback( this.OnReceive ), so ); allDone.WaitOne(); } } catch ( Exception e ) { Console.WriteLine( e.ToString() ); } }
private void Begin() { m_Message = m_Spawner.Spawn(); try { m_Socket.BeginReceiveFrom(m_Message.Package, offset: 0, size: m_Message.Package.Length, socketFlags: SocketFlags.None, remoteEP: ref m_ReceiveEndPoint, callback: End, state: null); } catch (SocketException e) { var error = SocketError.Success; error = e.SocketErrorCode; m_Message.SetError(error); m_Message.SetEndPoint(m_ReceiveEndPoint); lock (m_ReceivePackages) { m_ReceivePackages.Add(m_Message); } Begin(); } catch (Exception e) { } }
private IAsyncResult CreateListener() { _testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _testSocket.Bind(new IPEndPoint(IPAddress.Any, 12721)); byte[] inbuffer = _bufferPool.Dequeue(); EndPoint ep = new IPEndPoint(IPAddress.Any, 1234); return _testSocket.BeginReceiveFrom(inbuffer, 0, inbuffer.Length, SocketFlags.None, ref ep, null, null); }
/** * Connect and receive data for the thread */ public override void process() { this.receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this.bindEndPoint = new IPEndPoint(IPAddress.Parse(this.host), this.port); this.recBuffer = new byte[this.BufferSize]; receiveSocket.Bind(bindEndPoint); receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length, SocketFlags.None, ref bindEndPoint, new AsyncCallback(MessageReceivedCallback), (object)this); }
public Bf2Available() { // Creates an IPEndPoint to reference the IP Address and port number of the sender. EndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // Bind to local address and begin accepting connections UdpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); UdpSock.Bind(new IPEndPoint(IPAddress.Loopback, 27900)); UdpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref RemoteIpEndPoint, DoReceiveFrom, UdpSock); }
public MulticastCommandServer(string uid) { this.uid = uid; this.DscLog = new DscLog(); this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); EndPoint ep = (EndPoint)(new IPEndPoint(IPAddress.Any, MulticastEP.Port)); this.sock.Bind(ep); this.sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastEP.Address)); Trace.WriteLine(String.Format("Multicast JSON-RPC server: {0}:{1}", MulticastEP.Address, MulticastEP.Port)); sock.BeginReceiveFrom(dataIn, 0, dataIn.Length, SocketFlags.None, ref ep, new AsyncCallback(ReceiveData), ep); }
public void Start() { serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, Port); serverSocket.Bind(ipEndPoint); IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0); EndPoint epSender = (EndPoint)ipeSender; serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); }
/// <summary> /// Bind to the /// </summary> /// <param name="port"></param> public UdpListener(IPAddress serverAddress, int port, ServerFilter filter) { this.filter = filter; UDPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); UDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); UDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); UDPSocket.Bind(new IPEndPoint(serverAddress, port)); EndPoint tempRemoteEP = (EndPoint)sender; UDPSocket.BeginReceiveFrom(buff, 0, buff.Length, SocketFlags.None, ref tempRemoteEP, GotUdpMessage, tempRemoteEP); }
public ProxySocket(int port) { //Setup the socket and message buffer udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpSock.Bind(new IPEndPoint(IPAddress.Any, port)); buffer = new byte[1024]; //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); }
public void Start(int port, int buf_len) { buffer = new byte[buf_len]; // setup the socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Any, port)); // start listening EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, new AsyncCallback(DoReceiveFrom), socket); }
public void Start() { GkDatabase = DescriptorsManager.GkDatabases.FirstOrDefault(); serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1025); serverSocket.Bind(ipEndPoint); IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0); EndPoint epSender = (EndPoint)ipeSender; serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); }
public System.Threading.Tasks.Task <ReceivedUdpData> ReceiveAsync() { ThrowIfDisposed(); var tcs = new TaskCompletionSource <ReceivedUdpData>(); System.Net.EndPoint receivedFromEndPoint = new IPEndPoint(GetDefaultIpAddress(_Socket), 0); var state = new AsyncReceiveState(_Socket, receivedFromEndPoint); state.TaskCompletionSource = tcs; #if NETSTANDARD1_3 _Socket.ReceiveFromAsync(new System.ArraySegment <Byte>(state.Buffer), System.Net.Sockets.SocketFlags.None, state.EndPoint) .ContinueWith((task, asyncState) => { if (this.IsDisposed) { return; } try { if (task.Status != TaskStatus.Faulted) { var receiveState = asyncState as AsyncReceiveState; receiveState.EndPoint = task.Result.RemoteEndPoint; ProcessResponse(receiveState, () => task.Result.ReceivedBytes); } } catch (ObjectDisposedException) { if (!this.IsDisposed) { throw; } } //Only rethrow disposed exceptions if we're NOT disposed, because then they are unexpected. }, state); #else try { _Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, System.Net.Sockets.SocketFlags.None, ref state.EndPoint, new AsyncCallback((result) => ProcessResponse(state, () => state.Socket.EndReceiveFrom(result, ref state.EndPoint))), state); } catch (ObjectDisposedException) { if (!this.IsDisposed) { throw; } } //Only rethrow disposed exceptions if we're NOT disposed, because then they are unexpected. #endif return(tcs.Task); }
private void AwaitConnectionTimer_Tick(object sender, EventArgs e) { if (!_connected) { LogMessage("Server not found. I am server now!"); _awaitConnectionTimer.Stop(); _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _udpSocket.Bind(_ipep); EndPoint ep = (EndPoint)_ipep; _udpSocket.BeginReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ListenerRecieveCallback), _udpSocket); TcpServerInit(); } }
public static void Start() { _thread = new Thread(new ThreadStart(Run)); _thread.Start(); _connection = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500); _connection.Bind(new IPEndPoint(IPAddress.Any, 0)); obtainedData = new byte[100 * 1024]; obtainedIP = new IPEndPoint(IPAddress.Loopback, 12345); // should be useless? _connection.BeginReceiveFrom(obtainedData, 0, obtainedData.Length, SocketFlags.None, ref obtainedIP, new AsyncCallback(QueryReceived), null); Servers = new Dictionary<IPEndPoint, ServerData>(); }
private void AwaitConnectionTimer_Tick(object sender, EventArgs e) { LogMessage("Connection timer elapsed."); _awaitConnectionTimer.Stop(); // TODO: а нам это надо? if (!_connected) { _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _udpSocket.Bind(_ipep); EndPoint ep = (EndPoint)_ipep; _udpSocket.BeginReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ListenerRecieveCallback), _udpSocket); LogMessage("Waiting for clients..."); } }
public IAsyncResult BeginReceive(AsyncCallback callback, object state) { MyAsyncResult result = new MyAsyncResult() { Buffer = new byte[65535], EndPoint = _endPoint, Callback = callback, State = state }; result.AsyncResult = _socket.BeginReceiveFrom(result.Buffer, 0, 65535, SocketFlags.None, ref result.EndPoint, OnSocketCallback, result); return(result); }
private void button1_Click(object sender, EventArgs e) { if (socket != null) return; socket=new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP); socket.Bind(new IPEndPoint(IPAddress.Parse("10.2.21.129"), 100)); state.workSocket = socket; RcptRes = socket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, ref ClientEP, new AsyncCallback(Receive_Completed), state); }
public void Initialize() { ListenPort = Network.IsLookup ? Network.Lookup.Ports.Udp : Core.User.Settings.UdpPort; if (Core.Sim != null) return; UdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; UdpSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { 0 }, null); } catch { // will fail in mono } // listen bool bound = false; int attempts = 0; while( !bound && attempts < 5) { try { UdpSocket.Bind( new IPEndPoint( System.Net.IPAddress.Any, ListenPort) ); bound = true; EndPoint tempSender = (EndPoint) new IPEndPoint(IPAddress.Any, 0); UdpSocket.BeginReceiveFrom(ReceiveBuff, 0, ReceiveBuff.Length, SocketFlags.None, ref tempSender, new AsyncCallback(UdpSocket_Receive), UdpSocket); Network.UpdateLog("Network", "Listening for UDP on port " + ListenPort.ToString()); } catch(Exception ex) { Network.UpdateLog("Exception", "UdpHandler::UdpHandler: " + ex.Message); attempts++; ListenPort++; } } }
private async void StartUdpServer() { var udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Important to specify a timeout value, otherwise the socket ReceiveFrom() // will block indefinitely if no packets are received and the thread will never terminate udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100); udpListener.Bind(new IPEndPoint(IPAddress.Any, 54321)); var buffer = new byte[1500]; EndPoint sender = new IPEndPoint(IPAddress.Any, 0); while (true) { var result = await Task.Factory.FromAsync( (iar, s) => udpListener.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref sender, iar, null), iar => udpListener.EndReceiveFrom(iar, ref sender), null); if (result > 0) { if (firstPacket == DateTime.MinValue) firstPacket = DateTime.Now; var data = new byte[result]; Buffer.BlockCopy(buffer, 0, data, 0, result); ring.AddData(data); Frame f = null; do { f = ring.ReadFrame(); if (f != null) { f.Time = (DateTime.Now - firstPacket).TotalSeconds; var ev = OnFrameReceived; if (ev != null) { OnFrameReceived(this, new FrameReceivedEventArgs(f)); } } } while (f != null); } } }
public void Start(Configuration config) { this._config = config; this._shareOverLAN = config.shareOverLan; if (CheckIfPortInUse(_config.localPort)) throw new Exception(I18N.GetString("Port already in use")); try { // Create a TCP/IP socket. _tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint localEndPoint = null; if (_shareOverLAN) { localEndPoint = new IPEndPoint(IPAddress.Any, _config.localPort); } else { localEndPoint = new IPEndPoint(IPAddress.Loopback, _config.localPort); } // Bind the socket to the local endpoint and listen for incoming connections. _tcpSocket.Bind(localEndPoint); _udpSocket.Bind(localEndPoint); _tcpSocket.Listen(1024); // Start an asynchronous socket to listen for connections. Console.WriteLine("Shadowsocks started"); _tcpSocket.BeginAccept( new AsyncCallback(AcceptCallback), _tcpSocket); UDPState udpState = new UDPState(); _udpSocket.BeginReceiveFrom(udpState.buffer, 0, udpState.buffer.Length, 0, ref udpState.remoteEndPoint, new AsyncCallback(RecvFromCallback), udpState); } catch (SocketException) { _tcpSocket.Close(); throw; } }
public int Assign(int portIn = -1) { //Setup the socket and message buffer udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); bool fileFound = false; List<string> fileNameVec = FileSystem.ListFilesInDirectory(Globals.IpcPath); foreach (string fileNameCurrent in fileNameVec) if (fileNameCurrent == "udp_port") { fileFound = true; break; } int portCurrent; if (fileFound) { string udpPortStr = FileSystem.ReadTextFile(Globals.IpcPath + "\\udp_port")[0]; int.TryParse(udpPortStr, out portCurrent); endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), portCurrent); } else { if (portIn == -1) endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0); else endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), portIn); } udpSock.Bind(endPoint); int.TryParse(udpSock.LocalEndPoint.ToString().Split(':')[1], out portCurrent); FileSystem.WriteStringToFile(Globals.IpcPath + "\\" + "udp_port", portCurrent.ToString()); buffer = new byte[1024]; //Start listening for a new message. udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint, DoReceiveFrom, udpSock); return portCurrent; }
private void buttonConnect_Click(object sender, EventArgs e) { //bind the socket if (connected == false) { sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text)); sck.Bind(epLocal); //Connecting to Remote IP epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text)); sck.Connect(epRemote); //Listen for specific port: buffer = new byte[1500]; sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer); //disable connect button until new IP or Host is entered. textBoxState(false); //set the IPs and disable the button buttonConnect.Text = "End"; buttonSend.Enabled = true; connected = true; } else { // sck.EndConnect(); ASCIIEncoding aEncoding = new ASCIIEncoding(); byte[] disconnectMsg = new byte[1500]; disconnectMsg = aEncoding.GetBytes("Friend has disconnected"); sck.Send(disconnectMsg); sck.Shutdown(SocketShutdown.Receive); sck.Close(); textBoxState(true); buttonConnect.Text = "Connect"; buttonSend.Enabled = false; connected = false; listMessage.Items.Add("You have disconnected from the chat."); //sck.EndReceiveFrom(buffer , ref epRemote); } }
/// <summary> /// Async Listen Server for UDP reply from Onkyo Devices /// </summary> /// <param name="port">Listen Port</param> /// <param name="bufferSize">Receive message buffersize</param> public void Listen(int port = 50000, int bufferSize = 512) { try { _port = port; _bufferSize = bufferSize; _buffer = new byte[_bufferSize]; _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iEP = new IPEndPoint(IPAddress.Any, _port); EndPoint ep = iEP; _udpSocket.Bind(iEP); // Listen for data _udpSocket.BeginReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref ep, ReceiveData, _udpSocket); } catch (SocketException ex) { Debug.WriteLine("Error: {0} {1}", ex.ErrorCode, ex.Message); } }
void btnConnect_Click(object sender, RoutedEventArgs e) { try { string msgConn = tbName.Text + " connected"; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress serverIP = IPAddress.Parse(tbIp.Text); server = new IPEndPoint(serverIP, 30000); epServer = (EndPoint)server; byteData = Encoding.UTF8.GetBytes(msgConn); clientSocket.BeginSendTo(byteData, 0, byteData.Length > 1024 ? 1024 : byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null); bytes = new byte[1024]; clientSocket.BeginReceiveFrom(bytes, 0, 1024, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null); } catch (Exception ex) { MessageBox.Show("Connection Error: " + ex.Message); } }
protected void DoReceive() { lock (SyncRoot) { if (m_bReceive == false) { return; } System.Net.EndPoint ep = (System.Net.EndPoint)m_tempRemoteEP; try { if (m_Logger != null) { LogMessage(MessageImportance.Lowest, this.OurGuid, string.Format("Called DoReceive for {0}", s.LocalEndPoint)); } BufferSocketRef objRef = new BufferSocketRef(this); s.BeginReceiveFrom(objRef.bRecv, 0, m_nBufferSize, System.Net.Sockets.SocketFlags.None, ref ep, asyncb, objRef); } catch (SocketException e3) /// winso { LogError(MessageImportance.High, "SocketEXCEPTION", string.Format("{0} - {1}", e3.ErrorCode, e3.ToString())); return; } catch (ObjectDisposedException e4) // socket was closed { LogError(MessageImportance.High, "ObjectDisposedEXCEPTION", e4.ToString()); return; } catch (Exception e5) { LogError(MessageImportance.High, "EXCEPTION", e5.ToString()); return; } } return; }
public void Start(NetConfig config) //START SERVER WITH A CONFIG { //SPAWN A THREAD FOR THE NEW CONNECTION CHECKING FUNCTION. Thread checkThread = new Thread(new ParameterizedThreadStart(ConnectionCheckingThread)); checkThread.IsBackground = true; checkThread.Start(config.Timeout); //END ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); ServerSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0, 0, 0, 0 }, null); //Fixs the Exception : An existing connection was forcibly closed by the remote host. ServerSocket.Bind(new IPEndPoint(IPAddress.Any, config.Port)); Connection = new NetConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), config.Port)); EndPoint remoteSender = new IPEndPoint(IPAddress.Any, 0); try { ServerSocket.BeginReceiveFrom(DATA, 0, DATA.Length,SocketFlags.None, ref remoteSender, Handle_Receive, ServerSocket); } catch(Exception e) { #if DEBUG_OUTPUT Console.WriteLine("Exception: in BeginReceiveFrom: " + e.Message); #endif } }
public override void Start() { try { Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); S.Bind(EndPoint); S.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); while (true) { Next.Reset(); DatagramState DState = new DatagramState(); DState.ClientSocket = S; Console.WriteLine("listenning...."); S.BeginReceiveFrom(DState.Buffer, 0, DatagramState.BufferSize, 0, ref DState.EndPoint, new AsyncCallback(RecieveCallback),DState); Next.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.Message); } Console.Read(); }
public LanHandler(DhtNetwork network) { Network = network; Core = network.Core; // we need to listen on a static lan port common to all nodes in the operation // use the opkey to derive this common port byte[] hash = new SHA1Managed().ComputeHash(Network.OpCrypt.Key); ListenPort = BitConverter.ToUInt16(hash, 0); if (ListenPort < 2000) ListenPort += 2000; if (Core.Sim != null) return; LanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); LanSocket.EnableBroadcast = true; // listen - cant retry because listen port must be the same for everyone try { LanSocket.Bind( new IPEndPoint( System.Net.IPAddress.Any, ListenPort) ); EndPoint tempSender = (EndPoint) new IPEndPoint(IPAddress.Any, 0); LanSocket.BeginReceiveFrom(ReceiveBuff, 0, ReceiveBuff.Length, SocketFlags.None, ref tempSender, new AsyncCallback(UdpSocket_Receive), LanSocket); Network.UpdateLog("Network", "Listening for LAN on port " + ListenPort.ToString()); } catch(Exception ex) { Network.UpdateLog("Exception", "LanHandler::LanHandler: " + ex.Message); } }
private void Server_Load(object sender, EventArgs e) { try { // Initialise the ArrayList of connected clients this.clientList = new ArrayList(); // Initialise the delegate which updates the status this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus); // Initialise the socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // Initialise the IPEndPoint for the server and listen on port 30000 IPEndPoint server = new IPEndPoint(IPAddress.Any, 30000); // Associate the socket with this IP address and port serverSocket.Bind(server); // Initialise the IPEndPoint for the clients IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0); // Initialise the EndPoint for the clients EndPoint epSender = (EndPoint)clients; // Start listening for incoming data serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender); lblStatus.Text = "Listening"; } catch (Exception ex) { lblStatus.Text = "Error"; MessageBox.Show("Load Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void ContinueReceiving(IAsyncResult receiveResult, Socket listenSocket) { bool continueReceiving = true; while (continueReceiving) { FramingData data = null; if (receiveResult != null) { data = EndReceive(listenSocket, receiveResult); receiveResult = null; } lock (ThisLock) { if (!closed) { EndPoint dummy = CreateDummyEndPoint(listenSocket); byte[] buffer = this.bufferManager.TakeBuffer(maxMessageSize); receiveResult = listenSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref dummy, this.onReceive, new SocketReceiveState(listenSocket, buffer)); } } if (receiveResult == null || !receiveResult.CompletedSynchronously) { continueReceiving = false; Dispatch(data); } else if (data != null) { ThreadPool.QueueUserWorkItem(new WaitCallback(DispatchCallback), data); } } }
public void NetworkTargetUdpTest() { var target = new NetworkTarget() { Address = "udp://127.0.0.1:3002", Layout = "${message}\n", KeepConnection = true, }; string expectedResult = string.Empty; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Exception receiveException = null; var receivedMessages = new List<string>(); var receiveFinished = new ManualResetEvent(false); byte[] receiveBuffer = new byte[4096]; listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002)); EndPoint remoteEndPoint = null; AsyncCallback receivedDatagram = null; receivedDatagram = result => { try { int got = listener.EndReceiveFrom(result, ref remoteEndPoint); string message = Encoding.UTF8.GetString(receiveBuffer, 0, got); lock (receivedMessages) { receivedMessages.Add(message); if (receivedMessages.Count == 100) { receiveFinished.Set(); } } remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); } catch (Exception ex) { receiveException = ex; } }; remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); target.Initialize(new LoggingConfiguration()); int pendingWrites = 100; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; int toWrite = pendingWrites; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); expectedResult += "message" + i + "\n"; } Assert.IsTrue(writeCompleted.WaitOne(30000, false)); target.Close(); Assert.IsTrue(receiveFinished.WaitOne(30000, false)); Assert.AreEqual(toWrite, receivedMessages.Count); for (int i = 0; i < toWrite; ++i) { Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received."); } Assert.IsNull(receiveException, "Receive exception: " + receiveException); } }
public void Initialize() { try { IsServiceStarted = false; nUdpClientFlag = 0; //Using UDP sockets clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450); //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc). clientSocket.Bind(ourEP); //Receive data from any IP. EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); byteData = new byte[1024]; //Receive data asynchornously. clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref remoteEP, new AsyncCallback(OnReceive), null); } catch (Exception ex) { //sssMessageBox.Show(ex.Message, "VoiceChat-Initialize ()", MessageBoxButtons.OK, MessageBoxIcon.Error); cGlobalVars.AddLogChat("VoiceChat-Initialize > " + ex.Message); } }
System.IAsyncResult Utils.Wrappers.Interfaces.ISocket.BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { return(InternalSocket.BeginReceiveFrom(buffer, offset, size, socketFlags, ref remoteEP, callback, state)); }
/// <summary> /// Create a new instance of the server context type. /// </summary> private void CreateServerContext() { UdpServerContext socketServerContext = null; try { // Clear last error. ClearLastError(); // Create a new instance of the server context type socketServerContext = new UdpServerContext(_specificAddressFamily); socketServerContext.Socket = _socket; socketServerContext.Name = _serverName; socketServerContext.ReceiveSocketFlags = _receiveSocketFlags; socketServerContext.SendSocketFlags = _sendSocketFlags; socketServerContext.SendToServerHandler = _sendToServerHandler; socketServerContext.SendToServerInfoHandler = _sendToServerInfoHandler; socketServerContext.ReadBufferSize = READ_BUFFER_SIZE; socketServerContext.WriteBufferSize = WRITE_BUFFER_SIZE; socketServerContext.ServerRef = this; socketServerContext.Server = this; // If a time out has been set. if (_timeOut > 0) { socketServerContext.TimeOut = _timeOut; } // Create a new client data receive handler, this event // handles commands from the current client. socketServerContext.OnCommandSend += new UdpServerContextHandler(SocketServer_OnCommandSend); // Initalise the context. socketServerContext.Initialise(); // Increment the count. IncrementCount(); try { // Send the new connection to the caller. if (OnClientConnected != null) { OnClientConnected(this, socketServerContext); } } catch { } // Lock the socket receive process. lock (LockingSocket) { // Start receiving data from the client. _socket.BeginReceiveFrom(socketServerContext._readBuffer, 0, socketServerContext.ReadBufferSize, socketServerContext.ReceiveSocketFlags, ref socketServerContext.RemoteClient, new AsyncCallback(socketServerContext.DataReceiver), socketServerContext); } } catch (Exception ex) { // Clean-up if error. if (socketServerContext != null) { socketServerContext.Dispose(); } socketServerContext = null; SetLastError(ex); } }
public static bool Initialize() { try { EndPoint ep = new IPEndPoint(IPAddress.Any, 0); _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _listenSocket.Bind(new IPEndPoint(IPAddress.Any, Globals.Config.Udp.Port)); if (Type.GetType("Mono.Runtime") == null) _listenSocket.IOControl(-1744830452, new byte[] { Convert.ToByte(false) }, null); _listenSocket.BeginReceiveFrom(_udpBuffer, 0, _udpBuffer.Length, SocketFlags.None, ref ep, RecieveFromCallback, null); return true; } catch { return false; } }