I wrote the below code to get a string (encrypted) from the user, and I need to use a thread.
TcpListener TCPListen = new TcpListener(IP2, port);
TCPListen.Start();
TcpClient TCP = TCPListen.AcceptTcpClient();
NetworkStream NetStream = TCP.GetStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
byte[] Key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
CryptoStream CryptStream = new CryptoStream(NetStream,
RMCrypto.CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
StreamReader SReader = new StreamReader(CryptStream);
Ihe problem is that i should use the thread after the TCPListen.Start(); otherwise will get an error**(Only one usage of each socket address (protocol/network address/port) is normally permitted)**
How can I solve this problem?
Alternatively to moving the blocking calls to a new thread, you can use use BeginConnect, BeginReceive, BeginSend methods and their corresponding End(Connect | Receive | Send) as outlined here.
EDIT: RE: question below from OP…
Instead of calling
Connect(), you would callBeginConnect()and provideBeginConnect()a method to call when someone connects (known as a “Callback”). This Callback will get called so that you can do whatever work you need to do. The first thing your code should do is callEndConnect(). The issue is that callingConnect()blocks (ie, halts all code execution on that thread) until it returns. Using theBeginXXX()andEndXXX()side steps this issue. Its really too meaty of a topic to explain in any useful depth here. Study at the MSDN doc linked above. If you have specific questions after spending some time with it, post them back here and I’ll try to answer them. 🙂