32feet client connecting thread failing - c#

I'm trying to connect through the application I'm making as a client to my phone for testing purposes, but I'm missing something. After pairing the devices, the program should open a new thread on which it runs client.BeginConnect, but it only gets as far as "Starting connect thread...".
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(deviceInfo.DeviceName + " was selected. Attempting to connect.");
if (pairDevice())
{
updateUI("Device paired.");
updateUI("Starting connect thread...");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
}
else
{
updateUI("Pairing failed.");
}
}
private void ClientConnectThread()
{
updateUI("Attempting connect.");
client.BeginConnect(deviceInfo.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(BluetoothClientConnectCallback), client);
}
I tried reusing a thread I used for scanning for devices previously and pasted the BeginConnect there, but that just makes the program crash. I'm unsure of what error it might show, because I'm programming it on my PC, but can only test the program on another laptop using the .exe file.

You have created a thread, but you haven't asked it to start yet:
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start(); // <--- this starts the thread
See here for details
Of course, then you have another problem because you call BeginConnect (which is asynchronous) and then the function ends (and so will the thread).

Related

Running TCPListener from a Windows Service

I am trying to create a Windows service which listens on a particular port for an incoming serialized object and then performs some action, however every time I start I get the following error:
System.Net.Sockets.SocketException (0x80004005): Only one usage of each socket address (protocol/network address/port) is normally permitted
Here is the code that's running:
protected override void OnStart(string[] args)
{
Thread t = new Thread(Server.StartServer);
t.Start();
}
The StartServer method looks like this:
public static void StartServer()
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Loopback, 8889);
server.Start();
}
catch(Exception e)
{
//write to a log file and close
}
for (; ; )
//Some more code that handles the serialization etc
The message seems to state that something else is already listening on that socket however when I take a look using CMD and netstat -a I see nothing on that port, and it seems to occur regardless of what I change the listening port to. The exception occurs on the line "server = new TcpListener(IPAddress.Loopback, 8889);".
Why does this error occur and how am I able to make this work properly?
*Edited to note that I have also tried this as a console app and it seems to work, it only fails when running as a Windows Service

TCPClient won't connect from custom class

I'm facing a quite strange problem on Unity 5.2.0f3 64Bits. When I create my own custom class for a TcpClient connection, this one never gets connected. This is my simple class:
protected override void StartClient(string mod, string ip)
{
RunClient(ip, mod);
}
private ManualResetEvent connectDone = new ManualResetEvent(false);
private void connect_done(IAsyncResult ar)
{
connectDone.Set();
}
private void RunClient(string ip_host_name, string mode)
{
try
{
TcpClient client = new TcpClient();
client.BeginConnect(IPAddress.Parse(ip_host_name), 6666, new AsyncCallback(connect_done), client);
connectDone.WaitOne();
//Console.WriteLine("Connected");
SslStream lv_ssl_stream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
if (authenticate_server(lv_ssl_stream, client))
{
}
else
{
// Console.WriteLine("\nCouldn't authenticate the server");
}
client.Close();
}
catch (Exception e)
{
}
}
This is a custom class which doesn't inherit from MonoBehaviour, because the idea was it to run on a different thread. When I execute the Unity app, the class instance is properly created and also executed (with/out Thread, it's for both the same behaviour).
When the process comes across client.BeginConnect() the AsyncCallback() is fired, but the client.connected is still false.
When I replace client.BeginConnect() with client.Connect() the process will hang there, and when it's not executed in a different thread, the Unity framework just dumps. (Not Responding)
I developed the class first on .Net 2012 and could execute it with all expected results (no errors).
EDIT:
When I create and ran TcpClient.Connect() in MonoBehaviour, the TcpClient gets connected to my server, but this isn't an solution for me as it's a lot of data which is getting returned.
Has somebody faced this type of problem?
Workaround for that issue was to create a normal unity C# script, placing there the whole client code.
Unity is still buggy, because the first time the code was copied, it didn't work but commenting out/in it worked (copied code of RunClient() )...

Need help in "Socket Programming" using Visual C# (Dot Net Framework 4.0)?

Recently, I was given an assignment...
"To develop a Windows Forms application which can be installed on various windows machines at an office or enterprise. There would be a database in just one machine(ALPHA machine).. This database would be used by applications on other Beta machines to access data. The application would itself manage to check if it is an Alpha or a Beta (Has Database file with it?) and hence has to act as a server or a client."
I can do everything except the Network and Inter-Application Communication requirements. So, I started to learn Socket Programming over the Internet and I have gone through this link...
The idea I am working on is...
To have the client send the message to server.
To have the server accept this message and put this message in queue.
Read the message to get Client's IP Address and the its Request for Data.
Apply this request on database and get the result.
Convert the result in string.
Send it to the requesting client.
I can manage to perform steps 3,4 & 5. I am stuck on 1, 2 & 6.
Towards this...
I have created a function for Server as well as for client who return the Sockets when called. I create a separate function as I like my code to be clean, tidy and understandable after years.
Check my code below...
For Server...
private Socket GetServerReady()
{
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Any, 8000);
Socket newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newSock.Connect(RemoteEP);
newSock.Listen(10);
return (newSock);
}
You will notice there is no Accept() method anywhere, This is because I wish to call it like below for further use...
Socket CltSock = GetServerReady().Accept();
The Code for Client is...
private Socket GetClientReady()
{
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Parse(txtBxHost2.Text.Trim()), 8000);
Socket ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSock.Connect(RemoteEP);
return (ServerSock);
}
Finally, The questions are....
"Where is the appropriate place to call the functions I wrote above?"
"Should I call the Server and Client Function in Form_Load() Event?"
"What must be the next step towards my main intention which is point 1,2 & 6 mentioned above?"
I don't expect the full code that I can just copy as it is. Just the correct procedure and a little detail over the concept would do.
I would be using just a single PC for testing purpose. Also, another limitation is, It would all be coded in a single application. I don't want to write two separate applications for client & server.
I hope I made it all clear for you to understand.
Thanks a Lot.
Awaiting the response.
I was struggling to get things done and somehow managed to get the solution.
Below is my solution:
Server Side code:
(I put this code in a function which loops back the execution if any exception is caught)
private void Looper()
{
int i = 0;
int AttemptCount = 1;
while (i == 0)
{
try
{
TcpListener tL = new TcpListener(Network.GetLocalIPAddress(), 56009);
tL.Start(10);
Socket tS = tL.AcceptSocket();
if (tS.Connected)
{
NetworkStream nS = new NetworkStream(tS);
StreamReader Reader = new StreamReader(nS);
Output = Reader.ReadToEnd().Trim();
Reader.Close();
nS.Close();
tS.Close();
tL.Stop();
//If Done, End Execution
i = 1;
}
else
{
MessageBox.Show("The connection to the client is broken or failed..!!\n\nPlease check connection and try again.","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch (SystemException ex)
{
//If Not, Loop Execution Again
if (MessageBox.Show("Exception: " + ex.Message + "\n\nAttempt Count: " + AttemptCount + "\n\nDo you want to terminate the transmission?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
{
i = 1;
ResetTimer.Stop();
}
else
{
i = 0;
AttemptCount++;
}
}
}
}
When above function is called, The server waits to accept any incoming socket. If there is any error somewhere due to port re-usage or anything, It loops back itself and resets the server. (So, we don't have to manually call the server function again & again.)
Once the server accepts any incoming socket, the execution ends up successfully. Lot's of time we don't want to keep invoking server even after a successful reception. So, I, instead of calling this function in a button "click_event", I called it in a timer Tick_Event. So, the human need is eliminated at server side.
This leads to a problem. Once the server starts waiting to accept, It is in blocking mode.
It hangs all the processes and controls in same thread. So, I moved the call to above function to BackgroundWorker's "Do_Work" Event.
Check below Code:
private void GetServerReady()
{
if (!bW.IsBusy)
{
bW.RunWorkerAsync();
txtBxHistory.Text += "\r\n" + Output;
}
}
private void bW_DoWork(object sender, DoWorkEventArgs e)
{
Looper();
}
private void ResetTimer_Tick(object sender, EventArgs e)
{
GetServerReady();
}
"bW" is "BackgroundWorker".
"Output" is a variable I defined globally.
The reason we need a variable is that,
BackgroundWorker has its own thread to execute the code placed in its "Do_Work" Event. So, a TextBox from our application's thread can't be used by BackgroundWorker to store the received output. Doing this to a variable and then setting TextBox's Text property to this variable does the trick.
Client Side code:
private void btnSend_Click(object sender, EventArgs e)
{
TcpClient socketForServer;
try
{
socketForServer = new TcpClient(txtBxDestIP.Text.Trim(), 56009);
}
catch
{
MessageBox.Show("Failed to connect to server at " + txtBxDestIP.Text.Trim() + ":999", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
NetworkStream networkStream = socketForServer.GetStream();
StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
try
{
string InputString;
InputString = Network.GetLocalIPAddress() + ": " + txtBxData.Text;
streamWriter.Write(InputString);
streamWriter.Flush();
socketForServer.Close();
txtBxHistory.Text += "\r\nMe: " + txtBxData.Text.Trim();
txtBxData.Clear();
}
catch
{
MessageBox.Show("Exception reading from Server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
streamWriter.Close();
networkStream.Close();
socketForServer.Close();
}
"txtBxDestIP" is a TextBox having the Destination IP address as Text.
"txtBxData" is a TextBox having the text to be sent.
This code works flawless for me. With above solution I can achieve all my motives from step 1 to 6 (Mentioned in the question above.)
I hope it helps others too. Please suggest if there is a better and efficient way to perform this.
Thanks.
Regards.

Trying to force my app to close and the TcpListener to stop listening - stackOverflow

My dual-role app (in its role as "Server" running on another machine) fails to actually shut down when I close it (it is still in the "Processes" list in Task Manager after I close the app).
I don't know if it is staying "live" because its TcpListener class is still listening, or if the TcpListener class is still listening because the app hasn't really shut down.
So, I added two pieces of code:
1) The last line here (listener.Stop()):
static void Server()
{
TcpListener listener = new TcpListener(IPAddress.Any, 51111);
listener.Start();
var shouldExit = false;
while (!shouldExit)
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
if (msg == "exit")
// Client told us to exit...
shouldExit = true;
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " back atcha!");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
//listener.EndAcceptTcpClient; //unnecessary because AcceptTcpClient() is wrapped in a "using"?
listener.Stop();
}
...and:
2)
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Close(); // The app/process is staying "live" even after shutting down the app...maybe this will help?
}
// but on closing the app, I got: "System.StackOverflowException was unhandled" here...?
Why would there be a Stack overflow when calling Close?

C# problem with multi-clients server application

I have a server application and a client application.
I'm using socket to communicate between server and client. Everything works fine if there's only one client connect: uploading, downloading all work well.
But if there's another client connect (I start the client application again, which means there're 2 client apps and 1 server app running on my computer), my server starts to mess up: server doesn't receive file upload from client, client couldn't download from server.
In server code, I already used multithreading for each client connection so I can't figure out the problem. Here is my server code:
private void ServerForm_Load(object sender, System.EventArgs e)
{
//...
Thread th = new Thread(new ThreadStart(ListenForPeers));
th.Start();
}
public void ListenForPeers()
{
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serversocket.Blocking = true;
IPHostEntry IPHost = Dns.GetHostEntry(server);
string[] aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
IPEndPoint ipepServer = new IPEndPoint(addr[0], 8090);
serversocket.Bind(ipepServer);
serversocket.Listen(-1);
while (true)
{
clientsock = serversocket.Accept();
if (clientsock.Connected)
{
total_clients_connected++;
AppendText("Client connected...");
Thread tc = new Thread(new ThreadStart(listenclient));
tc.Start();
}
}
void listenclient()
{
// start communication
}
Is there something wrong with my server code that makes it unable to become a multi-clients server system? Help is really appreciated. Thanks in advance.
It looks like you've defined your clientSocket as a global variable to be used by all server threads, instead you want it to be a local reference for each thread. You can do this with a ParameterizedThreadStart:
public void listenForPeers()
{
//Setup the server socket
while(true){
Socket newClient = serverSock.Accept();
if(newClient.Connected){
Thread tc = new Thread(new ParameterizedThreadStart(listenclient));
tc.start(newClient);
}
}
}
void listenclient(object clientSockObj)
{
Socket clientSock = (Socket)clientSockObj;
//communication to client via clientSock.
}
First, you're setting your socket's Blocking property to true. This will block any requests until the previous ones finish...
See here: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.blocking(VS.80).aspx
If you are in blocking mode, and you
make a method call which does not
complete immediately, your application
will block execution until the
requested operation completes. If you
want execution to continue even though
the requested operation is not
complete, change the Blocking property
to false. The Blocking property has no
effect on asynchronous methods. If you
are sending and receiving data
asynchronously and want to block
execution, use the ManualResetEvent
class.
You might want to reconsider doing it this way, and instead use WCF or maybe a web service for uploading the files... it'll be a lot easier, and IIS will handle the threading for you. It's pretty easy to write a web service to upload a file...
http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx
try this
const int noOfClients = 5;
for(int i=0;i<noOfClients;i++)
{
Thread th = new Thread(new ThreadStart(ListenForPeers));
th.Start();
}

Categories