I want to start by saying I've read dozens of tutorials on chat programs, except everyone does it differently and now I'm a little confused. I think I have this right, but input is greatly appreciated.
I'm making a small, direct chat program which only chats with another computer. The stream is encrypted using CryptoStream. My problem is that my CryptoStream won't send the message unless I use .Close(), but then that closes the socket. So my first message will be received, but the second message throws an error.
I should say under my current code, the chat works fine using .Flush() on the network stream itself if I take CryptoStream completely out of the picture.
When I create my class, it starts a new thread which will do the listening
Code:Public Sub New(ByVal Key As String) MyBase.New() readThread = New System.Threading.Thread(AddressOf ReadMessage) readThread.IsBackground = True readThread.Start() End SubCode:Private Sub ReadMessage() Dim TCPinbound As TcpClient Dim listener As New TcpListener(Net.IPAddress.Any, 12345) listener.Start() Do While True Dim IncomingMsg As String TCPinbound = listener.AcceptTcpClient Dim DecryptStream As New CryptoStream(TCPinbound.GetStream(), RMCrypto.CreateDecryptor(Password, IV), CryptoStreamMode.Read) Dim reader As New IO.StreamReader(DecryptStream) IncomingMsg = reader.ReadToEnd If Not IncomingMsg = Nothing Then RaiseEvent TransmissionRecieved(IncomingMsg) End If Loop End Sub
This is my code for sending
Those last three lines written as such will successfully send one message. Trying to send a second says the socket is closed. Removing the .Close() prevents anything from being sent, until I quit my application and then a stream is received one final time.Code:Public Sub ConnectToClient(ByVal HostName As String) TCPoutbound = New TcpClient(HostName, 12345) End Sub Public Sub SendMessage(ByVal str As String) CryptStream = New CryptoStream(TCPoutbound.GetStream, RMCrypto.CreateEncryptor(Password, IV), CryptoStreamMode.Write) Dim output() As Byte = Encoding.ASCII.GetBytes(str) CryptStream.Write(output, 0, output.Length) CryptStream.Flush() CryptStream.FlushFinalBlock() CryptStream.Close() End Sub




Reply With Quote