Create some TCP connections in C #, then wait

I am currently creating a Windows service that will create TCP connections to multiple machines (the same socket on all computers) and then listen to the "events" from these computers. I am trying to write code to create a connection, and then create a stream that listens for a connection waiting for packets from the computer, then decodes incoming packets and calls a function depending on the packet payload.

The problem is that I'm not quite sure how to do this in C #. Does anyone have any helpful suggestions or links that can help me do this?

Thanks in advance for your help!

+3
source share
4 answers

You can have asynchronous reception for each socket connection and decode the data coming from other computers to perform your tasks (here you can find useful information about asynchronous methods: http://msdn.microsoft.com/en-us/library/2e08f6yc .aspx ).

To create a connection, you can:

Socket sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(new IPEndPoint(address, port));

Similarly, you can create multiple connections and store links in a dictionary list (depending on what you prefer).

To receive data asynchronously in a socket, you can:

sock.BeginReceive(buffer, 0, buffer.len, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

The method OnDataReceivedwill be called when the receive operation completes.

In OnDataReceivedyou should do:

void OnDataReceived(IAsyncResult result)
{
   int dataReceived = sock.EndReceive(result);
   //Make sure that dataReceived is equal to amount of data you wanted to receive. If it is
   //less then the data you wanted, you can do synchronous receive to read remaining data.

  //When all of the data is recieved, call BeginReceive again to receive more data


  //... Do your decoding and call the method ...//
}

Hope this helps you.

+2
source

, , , , . , . .NET 1 , 1 .

, , ( . ), , Windows " " , , , - .

, BeginAccept, BeginReceive, BeginSend ..

, , Socket.Select . . , , , .

, " " , , . , Accept, Receive, Send .. , .

+4

, accept() . , , , .

0

, , WCF, ? Windows IIS. , , , , . . , , / . , REST .

, , .

...

0

Source: https://habr.com/ru/post/1735168/


All Articles