But my code below is not accepting the connection.
The code from eggheadcafe works with the server code from eggheadcafe. So I know I did something wrong in my code for my windows application.
The complete error message is
Code:
System.Net.Sockets.SocketException was unhandled
ErrorCode=10061
Message="No connection could be made because the target machine actively refused it"
Source="System"
StackTrace:
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at TCP___CLient.TCPCli.Main() in C:\Documents and Settings\Owner\Local Settings\Application Data\Temporary Projects\TCP - CLient\Module1.vb:line 7
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
vb Code:
Public Class Form1
Dim listeners(9) As Net.Sockets.TcpListener
Dim thrListen As New Threading.Thread(AddressOf DoListen)
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
For i As Integer = 0 To 9
listeners(i).Stop()
listeners(i) = Nothing
Next
thrListen.Abort()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim basePort As Integer = 44000
For i As Integer = 0 To 9
listeners(i) = New Net.Sockets.TcpListener(Net.IPAddress.Any, basePort + i)
I think I may have figured out more of the puzzle. It looks like the Client application is sending an array of bytes, and the server applicaiton is trying to receive a string. I don't know if this has anything to do with it or not.
[edit]
here is the client app part from the eggheadcafe website that is sending the data.
vb Code:
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect("192.168.1.100", 45000)
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
Ok, I wrote a client and server (Sender and receiver) I am still not getting the data from one app to the other correctly. I get 97, which does correspond to the ascii code value for lower case 'a' but, I have to close the stream, then close the connection before it will work. Is this how I am suppose to be sending information? Request connection, send data, close stream, close connection... For every single message? Even if I want someone to be connected, and be sending data back and forth?
This is my Server.
vb Code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim listeners(9) As Net.Sockets.TcpListener
Dim thrListen As New Threading.Thread(AddressOf DoListen)
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
For i As Integer = 0 To 9
listeners(i).Stop()
listeners(i) = Nothing
Next
thrListen.Abort()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim basePort As Integer = 44600
For i As Integer = 0 To 9
listeners(i) = New Net.Sockets.TcpListener(Net.IPAddress.Any, basePort + i)
Next
thrListen.Start()
End Sub
Private Sub DoListen()
Dim client As Net.Sockets.TcpClient
Dim TempString As String
TempString = ""
Dim sr As IO.StreamReader
Do
For i As Integer = 0 To 9
Try
listeners(i).Start()
client = listeners(i).AcceptTcpClient
sr = New IO.StreamReader(client.GetStream)
TempString = sr.Read
MsgBox("TcpListener " & i & " recieved the following:" & vbNewLine & TempString)
Catch
MsgBox(Err.Description)
End Try
Next
Loop
End Sub
End Class
This is my Client.
vb Code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim client As Net.Sockets.TcpClient
Dim sw As IO.StreamWriter
client = New Net.Sockets.TcpClient
Try
client.Connect("192.168.1.100", 44600)
sw = New IO.StreamWriter(client.GetStream)
sw.Write("a")
sw.Close()
client.Close()
Catch
MsgBox(Err.Description)
End Try
End Sub
End Class
Last edited by rack; Jul 12th, 2007 at 03:05 AM.
Please RATE posts, click the RATE button to the left under the Users Name.
Once your thread has been answered, Please use the Thread Tools and select RESOLVED so everyone knows your question has been answered.
I just wrote a udp listener the other day, and to avoid this problem I used a background worker, and inside that thread was an infinite loop which done the listening, if I received some bytes, I would pass them in the report progress event, and handled decoding the bytes there, I just always sent 0 for progress and Bytes() as the userstate object param. It worked perfectly, and is quite simple with no need to worry about delegates and invoking other controls...
I will upload it tomorrow if you want, all it does is send bytes to local host, and receives them in the BGworker, the host and listener are in the same class as to make it more readable, and it uses a library called TinyUDP for the host...
Anything will help, dunno how different the coding is for UDP and TCP. Also I just noticed I had some werid bit of dislexia when I wrote the title to this, I have now changed it to TCP instead of LCP, haha.
Please RATE posts, click the RATE button to the left under the Users Name.
Once your thread has been answered, Please use the Thread Tools and select RESOLVED so everyone knows your question has been answered.
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Ok, I got the listener to work, but I have a few final questions. If anyone knows please could you answer. I haven't really gotten many responces to this thread.
For some reason when I send data into the datastream, if I use the .write command on the networkstream, 3 different times, my listener will read it all in one time, instead of reading it three different times as three different messeges. Do I have to call a read after a Write?
I don't think it matters which way I went about getting information from the stream, the key was to read and write both in bytes.
Below is the code from the Server (tcpListener)
The following are the text boxes, and there purposes.
TxtChat - This is the chat window/box.
TxtPort - This is the TCP/IP port address to listen on.
TxtUserList - This is the textbox that shows which users have logged in.
TxtMessege - This is where the user will type the messege to send to the others.
The following are the two buttons, and there purposes.
BtnSend - Button that the user clicks to send a messege contained in the txtmessege textbox to the other user.
BtnListen - This button starts the listening (server) interface.
vb Code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim thrListen As New Threading.Thread(AddressOf DoListen)
Dim MyDataStream As System.Net.Sockets.NetworkStream
Dim Client As Net.Sockets.TcpClient
Dim tstServer As Net.Sockets.TcpListener
' This delegate enables asynchronous calls for setting
' the text property on a TextBox control.
Delegate Sub SetTextCallback(ByVal [text] As String)
Private Sub Form1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave
MyDataStream.Close()
tstServer.Stop()
thrListen.Abort()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub BtnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnListen.Click
tstServer = New Net.Sockets.TcpListener(Net.IPAddress.Any, Int(Val(TxtPort.Text)))
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Sorry, no help from my side, because I seem to have a related problem. In your last post you stated that you send 3 messages and they get recieved as one, are you sending from a client and when is the message been displayed (is the connection still open).
My listener will not display the messages sent by a client until the client closes the connection????
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Do you do those 3 .write commands using 3 separate button-clicks or are you doing it by code (which would be faster). In the last case it sounds like the "normal" operation I 've seen using VB6 Winsock for a TCP connection. I had to parse each message since I had multiple occasions when several messages where received a one message. At least you got the messages!
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
|-| is what I use to "split" the data". I figured just one character might be too easy for someone to accidently type.
I send three .write commands by code. In the code below, I tried doing a .Write, then .Read, then .Write, then .Read.
The messege from the CLient "NewUser:|-||-|Jeremy" is sent, and received.
The messege from the Server "RCVD" is sent, and received by the client.
The remaining messeges from the Client are never received by the server. It's as if the program just skips over them.
Posting the Client that sends the data. And the updated Listener (server)
CLIENT
vb Code:
Imports System.Net.Sockets
Imports System.Text
Class TCPCli
Shared Sub Main()
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect("192.168.1.100", 45000)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("NewUser:|-||-|Jeremy")
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
It doesn't work with NoDelay=True for me either!
I'm just trying to Send a message from Client, Disconnect (now the Server gets the message) and reconnect. Doing that via the controlbuttons (by hand) works fine, however if I change the Send routine and put connection_Close and Connect in it it doesn't do it. Maybe I have to wait for sencomplete (if I get something like that). This would be on the client side!
[Edit] Using the Sendcomplete for disconnecting and connecting does the job, now I have to make that into a VB2005 Clinet instead of a VB6 one!
Last edited by opus; Jul 17th, 2007 at 01:26 PM.
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
rack, I see one difference in the TCPListener from your code compared to mine, you start the listener in your DoListen Sub, I do that in the Btton_Click routine where the thrListen is also started.Although the outcome is the same (messages from the client don'T come thru) your code is forcing my cpu to be at 100% all the time, while is only doing that until the client connected!
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Hi, rack, I'm still doing further research.
It looks to me as if the DoListen Sub is stopped when the Client gets accepted "Client = tstServer.AcceptTcpClient". The next time this routine is jumped to is when the client closes the connection? The problem is I don't understand why!
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Here is that UDP example I posted about before...
Its UDP not TCP even thaugh the zip says TCP, but who cares, it sends and receives bytes and encodes them to ascii...
This example has 4 sub routines, form load, background worker do work, report progress, and a button click, all are quite simple to understand, I have only tested it sending to 127.0.0.1 and have not encountered 1 problem...
Re: [2005] TCPListener, Threading, Error. (not sending until close of stream)
Yeah I notice that for whatever reason, the server will receive the first messege, send a responce, and then, for whatever reason in my code, never again tries to get the data from the stream. I'm so close to the answer I can taste it, if someone knows what stupid coding mistake i'm making, please tell me.
Please RATE posts, click the RATE button to the left under the Users Name.
Once your thread has been answered, Please use the Thread Tools and select RESOLVED so everyone knows your question has been answered.
Here is my working TCP Server(tcplistener), and the test User(tcpclient)
The server only supports one user so far. I'm going to create a class/structure that will hold the information for 4 users to connect.
The objects on the form are the same from the earlyer posts.
If anyone can inform me of a better way for TCP connection (not UDP) let me know, this is all i've found, reading, testing, trying random changes to code, etc.
Anyways, hers the server.
vb Code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim thrListen As New Threading.Thread(AddressOf DoListen)
Dim MyDataStream As System.Net.Sockets.NetworkStream
Dim Client As Net.Sockets.TcpClient
Dim tstServer As Net.Sockets.TcpListener
Dim ClientStatus As Integer
' This delegate enables asynchronous calls for setting
' the text property on a TextBox control.
Delegate Sub SetTextCallback(ByVal [text] As String)
Private Sub Form1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave
MyDataStream.Close()
tstServer.Stop()
thrListen.Abort()
End Sub
Private Sub BtnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnListen.Click
tstServer = New Net.Sockets.TcpListener(Net.IPAddress.Any, Int(Val(TxtPort.Text)))
'start the listening
tstServer.Start()
'Make sure the Thread closes if the application does
The split command on line 107 of the most recent server code snipet showing in the post just before your post.
[EDIT]
Good night, i'm going to bed now, the happiness in me is overwhelmed by the lack of sleep.
[EDIT 2]
Also, I know that what is happening is, while reading, I am reading the length of the read BUFFER, not the length of the read DATA. I don't know how to gather the length of the read DATA. I tried changing the tcpclient.SendBuffer on the User (client) but I believe because the Receive buffer is still 8092 or something it ends up getting a 8093 lenth byte array/string.
So if you find out how to check the Receive read DATA let me know.
Other then the way I am currently using (flagging the end of the messege).
Other then sending the length of the messege with the messege, before the messege, (and useing the mid fucntion still).
Last edited by rack; Jul 18th, 2007 at 02:23 AM.
Please RATE posts, click the RATE button to the left under the Users Name.
Once your thread has been answered, Please use the Thread Tools and select RESOLVED so everyone knows your question has been answered.
Sendind and receiving works like a charm, however I have a problem if the client disconnects. Your code will receive empty messages in a endless loop.
I put in this change:
Code:
If ClientStatus >= 2 Then
If ClientStatus > 2 And TempString = "" Then
Exit Do
End If
' Read the stream into a byte array
Dim bytes(Client.ReceiveBufferSize) As Byte
MyDataStream.Read(bytes, 0, CInt(Client.ReceiveBufferSize))
' Return the data received from the client to the txtchat textbox.
TempString = Encoding.ASCII.GetString(bytes)
Me.SetText(TempString)
ClientStatus = 3
End If
The Tempstring is "" when the first empty message arrives after disconnecting, however the Check Tempstring="" returns FALSE! I don't get it????
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
OK, will give it try tonight (I my family will give me the time, we're just prior leaving for summer-vacation).
I see your checking for Client.connected=False, I checked on that, but it showed true??? all the time, although the connection was closed (without sending anything)from the other side. That'S the reason I was doing this try with the ClientStatus=3 and TempString="". I'm still wondering why a TempString="" would make a FALSE although TempString=""??
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!
Here are the two projects.
Both have similar functions in them. Both are windows applications with textboxes, and buttons.
For some reason, the threading on the Client makes the CPU usage jump to 50%, I don't know why, because I don't know much at all about threading. If anyone sees my error, let me know please.
Tcp - NS - Listener is the server.
TCP - CLient 2 is the User.
Open the Listener, click Listen.
Open the CLient, click Connect.
Make sure to edit the IP address to whatever you want to use 127.0.0.1 or whatever.
Tested it, the problem with the closed connection remains, my Client.Connected is still true, that way your If Clause doesn't do it. The check with an empty Tempstring would do it, however out off an unknown reason " TempString = "" " returns FALSE altough Tempstring="" ????? I tried it with also with VbNullChar and Nothing. I'm out off any clue!
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button Wait, I'm too old to hurry!