how to convert from UDP to TCP? For example I'm used this code for UDP:

Socket peer1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
UnicodeEncoding coding = new UnicodeEncoding();
byte[] pp = coding.GetBytes(ping);
peer1.SendTo(pp, receiverIp);
peer1.SendTo(txtBuf, txtBuf.Length, SocketFlags.None, receiverIp);

How to write it use TCP protocol??? Because my code is large, I only want some of codes change.
And another question:
How to define maximum buffer on receiver when I received packet for UDP and TCP?

Edited by mike_2000_17: Moved to C#, correct code-tags and spelling

4 Years
Discussion Span
Last Post by nmaillet

how to convert from UDP to TCP

Just Google some C# TCP socket tutorials and read through the MSDN class reference for the Socket class. There is alot to go over, so I'm not going to post everything here. For starters though, during Socket initialization, you'd change it to this:

Socket peer1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Using a stream (which you have to when using TCP) essentially means you read it like you would for a file (with delay and such). Packets are still being used in the backend, but you can't directly access them.

You would then have to call the Bind() method, to bind the socket to a particular local end point and port number (you can use IPAddress.Any if you want the system to assign it on connection).

Now, you would either call Connect() or Listen(), depending on if you'll be acting as the client or the server. You can still use SendTo() to send data, but its unnecessary, as each TCP socket will only have one remote end point. You'll have to create multiple sockets if you are communicating with more than one remote end point.

how to define maximum bufer on receiver when i received packet for UDP and TCP

I'm not sure what you mean. You can set the ReceiveBufferSize property to specify the internal buffer. If you're talking about the byte array (your buffer), then ReceiveFrom() and Receive() both have overloads to specify the maximum number of bytes to read.

To start look at System.Net.Sockets.Socket. It describes the methods I mentioned in more detail.

Edited by nmaillet

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.