Hi to all,
I want to connect a device [a kind of modem] over TCP-Protocol.
The device could be considered as a client. Over a program I want to connect to this device. The program is located on a server and has a special port open and a static ip.
How can I do it?
Here is my code :
// where ip= 10.0.0.50 and port= 5050, established for the server!
TcpListerner listener;
if listener!= null)
{
listener.Stop();
}
listener= new TcpListener(ip, port);
listener.Start();
Socket socket;
if (!listener.Pending())
{
IAsyncResult ar = listener.BeginAcceptSocket(new AsyncCallback(DoAcceptSocketCallback), socket);
Thread.Sleep(15000); // try to connect in 15 seconds
if (socket != null && socket.Connected)
{
// if socket is connected
// put the code here or do nothing
}
else
{
if (socket != null)
{
socket.Close();
}
if listener!= null)
{
listener.Stop();
listener = null;
}
}
}
public void DoAcceptSocketCallback(IAsyncResult ar)
{
try
{
TcpListener listener = (TcpListener)ar.AsyncState;
if (listener != null)
{
// connected to socket :
socket = listener.EndAcceptSocket(ar);
}
}
catch
{
socket = null;
}
}
although I can not connect the device and I can not solve the hang problem by socket connection. I can not do anything on my form while this code is running cause of 15seconds to try connecting.