-
Help with TCP
Ok, I am developing an Application that uses TCP To listen for connections, and then when a message is sent to the server and then it alerts the IP that is running the server.
(Lets say the server is on a iPhone, and some how the iPhone gets a text message, which alerts a tcp server running in the background via a .jar, it would send the owner of the iPhone a message on the computer telling it it has a text. This is just an example though, but i think it gets the general idea across. And don't flame me because it sounds like an iPhone Rat, it's not. As i said, it's an example.)
I've been trying to do this, and i can connect to a TCP Server (using 127.0.0.1:8888 for testing purposes, will move to a solid IP and Port later)
I can start the server (its still buggy and under development) but i don't know how to connect to the server via an application, and when a certain message is received to alert the IP Running the server
My Server Code is:
Code:
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim infiniteCounter As Integer
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
infiniteCounter = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
next
Now i know that to connect you'd do something like
Code:
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
clientSocket.Connect("127.0.0.1", 8888)
serverStream = clientSocket.GetStream()
and i know i would have to use some sort of Byte() method to send/receive messages, but i'm at a loss on how to set it all up :o
Was wonderin' if anycone could help me?
-
Re: Help with TCP
Well I have did a good bit with TCP but I do not use the TCP Client class. Instead I do everything with the Socket Classes so I am a bit vauge with on it.
The 2 things that I see here are.
1: You should have an event that fires to accept the connection rather than a loop.
2: You should use a real Ip or better still PC Name.
I have some code somewhere for a server. I'll see if I can dig out a bit of it to point you in the right direction.
-
Re: Help with TCP
Here is some code I use to initialize my server. hport is set to the port number I want to use before the code gets to this point,
Code:
Dim hInfo As System.Net.IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim hIPAddress As IPAddress = Nothing
hIPAddress = hInfo.AddressList(0)
SocketHandler = New TcpListener(hIPAddress, hPort) ' Set the IP AND Port Number
SocketHandler.Start()
RRTimer.Interval = 100
RRTimer.Start()
I also have a timer which will check for connection attempts rather than a loop.
In the Timer elapsed event I have
Code:
If SocketHandler.Pending() Then
CurThreadStart = New ThreadStart(AddressOf ConnectionBegin) ' Set info for the new thread
CurThread = New Thread(CurThreadStart) ' Initialize the new thread variable
CurThread.SetApartmentState(ApartmentState.STA)
CurThread.Start() ' Start the thread
SyncLock CurThread ' Lock the thread for update
VAActiveThreads += 1 ' increment active threads
cInfo.ActiveClients += 1
CurThread.Name = "ClientCon" + VAActiveThreads.ToString ' Name the thread
Console.WriteLine(CurThread.Name & " Thread Started")
End SyncLock
End If
This will start a new thread when a connection attempt is made which will handle the connection.
This is where my code becoes very different as I am using the socket class but basically the idea is that in the sub that is called as the new thread you would
Create the client instance.
Accept the connection to the new client.
Enter a loop that checks for data present at the socket
receive data if it is there
check how long since last data was received and exit loop if time has expired other wise loop back and get more data if it arrives.
close the thread
For example here is some minor pieces from my sub
Code:
ClientSocket = SocketHandler.AcceptSocket
Do
If ClientSocket.Available > 0 Then
BytesReceived = ClientSocket.Receive(InBuffer)
Else 'no data was present
Thread.Sleep(50)
IdleTimeout += 1
End If 'ClientSocket.Available > 0
If IdleTimeout > 100 Or ShutdownAPP Then Exit Do
Loop
SyncLock ThreadLocker
ClientSocket.Disconnect(False)
ClientSocket.Close()
ClientSocket = Nothing ' Lock for updating
VAActiveThreads -= 1 ' decrement the current number of threads
End SyncLock
Mind you I have only included a small bit of the code to give you and idea of the structure and the code above uses some variables which are not defined in this snippet but hopefully you will get the idea.
-
Re: Help with TCP
Here is a little more related to the byte received method
This would be at the top of the sub outside the loop area
Code:
Dim InBuffer(1024) As Byte
Dim OutBuffer(1024) As Byte
Dim BytesReceived As Integer = 0
Dim BytesSent As Integer = 0
Dim InBoundQue As String = ""
for receiving data
Code:
If ClientSocket.Available > 0 Then
BytesReceived = ClientSocket.Receive(InBuffer)
InBoundQue += Encoding.ASCII.GetString(InBuffer, 0, BytesReceived) 'add new data to que
And for sending data
Code:
OutBuffer = Encoding.ASCII.GetBytes(DataStringToSend)
BytesSent = ClientSocket.Send(OutBuffer)
Again keep in mind I am using the socket class here TCPClient may use different methods.