receiving data from tcp port
I have some problems with a device brought for signal capturing (vilistus), as its software is supposed to send data to a tcp port (#123) during capturing and I used a c# code with a t开发者_C百科cp listener to receive the data from the same port but the program is blocked at the accepttcpclient()
command line and no data is received.
TcpClient client = this.tcpListener.AcceptTcpClient();
It sounds like a client isn't connecting to the listener. When you call AcceptTcpClient on a TcpListener the application will hang there waiting for a client to connect which seems to be the issue you're having.
You can get around this issue by doing a BeginAcceptTcpClient which will free the application and allow the program to continue executing while you wait for a client. When a client then connects a delegate will be called and then you can start processing the client, reading data etc. So for example:
class Comms
{
TcpListener listener;
TcpClient client;
// Starts listening for a tcp client
public void StartListener()
{
listener = new TcpListener(IPAddress.Any, 123);
listener.BeginAcceptTcpClient(new AsyncCallback(ClientCallback), listener);
}
// Callback for when a client connects on the port
void ClientCallback(IAsyncResult result)
{
listener = (TcpListener)result.AsyncState;
try
{
client = listener.EndAcceptTcpClient(result);
// From here you can access the stream etc and read data
}
catch (IOException e)
{
// Handle any exceptions here
}
}
}
Providing the client connects correctly you will then be free to access the clients NetworkStream and then read and write data to the client. Heres a quick reference and example for you to take a look at: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient.aspx
When it comes to the reading and writing of data you will have a similar lock up problem with the client's NetworkStream Read and Write functions. For this problem you have two possible solutions:
Set a timeout for the read and write functions, by setting the ReadTimeout and WriteTimeout properties of the NetworkStream.
Use a similar callback method as with BeginAcceptTcpClient by using the BeginRead and BeginWrite functions found in the NetworkStream.
Personally I prefer the second option as the first won't free the program until the timeout occurs but they're both viable options and it depends which one you'd prefer to implement. You can go here for more information about the NetworkStream: http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx
Hope this helps
It sounds strange that the device is being the client. Are you sure that you should not use tcpClient.Connect()
to the device on port 123?
Why?
- How should the device know that you got a server running? It can't try to connect forever.
- How do the device know that port 123 is free for your application in your PC?
精彩评论