Multiclient server-client c# - c#

so recently i asked a question about a problem i had in my server-client program and i could solve the problem even though the answers i got on the question didnt help at all (thanks anyway :] ), but now i have another problem, i need the program to make it a multiclient-server type of thing, and i dont really know what to do. I have doubts on the ParameterizedThreadStart, how i put it to work etc, i've searched on it, i know its a thread method but still dont know how the heck i use it, any ideas? thanks in advance.
Client Code:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) //connect to server
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.34"), 123); // sincronizacao do IP com a porta
try
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IP_End);
if (client.Connected)
{
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em background
backgroundWorker1.WorkerSupportsCancellation = true; // possibilidade de cancelar o fio
}
else
{
reconnect();
}
}
catch (SocketException exception)
{
MessageBox.Show(exception.Message.ToString());
reconnect();
}
}
public void reconnect()
{
try
{
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.34"), 123); // sincronizacao do IP com a porta
client.Connect(IP_End);
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
catch (SocketException exception)
{
MessageBox.Show(exception.Message.ToString());
reconnect();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text=(receive + "\n\r"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
}
Server Code:
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public String text_to_send;
public Form1()
{
InitializeComponent();
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if(client.Connected) //enquanto o cliente tiver conectado pode escrever para o servidor
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text= (text_to_send + "\n\r"); }));
}
else
{
MessageBox.Show("Envio Falhado!");
}
}
private void button1_Click(object sender, EventArgs e)
{
if (text_to_send != "" && textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
else {
MessageBox.Show("Escreva uma mensagem para ser enviada");
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
TcpListener Listener = new TcpListener(IPAddress.Any, 123);
Listener.Start();
client = Listener.AcceptTcpClient();
if (text_to_send != "")
{
text_to_send = "Conexão efetuada com sucesso...";
backgroundWorker2.RunWorkerAsync();
}
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
}
}
Server Code (working on it):
public Form1()
{
InitializeComponent();
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if(client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text= (text_to_send + "\n\r"); }));
}
else
{
MessageBox.Show("Envio Falhado!");
}
}
private void button1_Click(object sender, EventArgs e)
{
if (text_to_send != "" && textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
else {
MessageBox.Show("Escreva uma mensagem para ser enviada");
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e) // criar server
{
this.threadTcp = new Thread(new ThreadStart(ListenToClients));
Listener.Start();
client = Listener.AcceptTcpClient();
if (text_to_send != "")
{
text_to_send = "Conexão efetuada com sucesso...";
backgroundWorker2.RunWorkerAsync();
}
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
}
private void ListenToClients()
{
Listener.Start();
while (true)
{
try
{
this.Listener.AcceptTcpClient();
client = Listener.AcceptTcpClient();
Thread threadClient = new Thread(new ParameterizedThreadStart(HandleClients));
threadClient.Start(client);
}
catch (Exception)
{
MessageBox.Show("error");
}
}
}
private void HandleClients()
{
//TcpListener Listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
Listener.Start();
client = Listener.AcceptTcpClient();
if (text_to_send != "")
{
text_to_send = "Conexão efetuada com sucesso...";
backgroundWorker2.RunWorkerAsync();
}
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
}
}
}

Related

C# TCP Client reconnect after closing and reopening client form

I wrote a chat application in C# WinForms. But if I close the client form (while this form is connected to the server form) and reopen the client form and try to reconnect, the client doesn't connect to the server..
How can I reconnect the client to the server if the application is closed and reopened?
(sorry for bad english)
Server:
public frmServer()
{
InitializeComponent();
textBox_Hostname.Text = GetLocalIPAddress();
Configuration Programmkonfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Port = Programmkonfiguration.AppSettings.Settings["Port"].Value;
textBox_Port.Text = Port;
toolStripStatusLabel_Serverstatus.Text = "deaktiviert";
toolStripStatusLabel_Serverstatus.ForeColor = Color.Red;
textBox_Output.Focus();
}
private string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void button_Send_Click(object sender, EventArgs e)
{
if (!(string.IsNullOrWhiteSpace(textBox_Output.Text)))
{
String s = "Server: " + textBox_Output.Text + Environment.NewLine;
textBox_Input.Text += s;
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
textBox_Output.Clear();
}
}
public void DoWork()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
this.SetText(Encoding.ASCII.GetString(bytes, 0, bytesRead));
}
}
private void SetText(string text)
{
if (this.textBox_Input.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox_Input.Text = this.textBox_Input.Text + text;
}
}
private void button_Starten_Click(object sender, EventArgs e)
{
IPAddress hostname = IPAddress.Parse(textBox_Hostname.Text);
int portNum = Convert.ToInt32(textBox_Port.Text);
listener = new TcpListener(hostname, portNum);
listener.Start();
Task TCPListener = new Task(() => AcceptTCP());
TCPListener.Start();
textBox_Input.Text += "Server gestartet." + Environment.NewLine;
button_Starten.Enabled = false;
toolStripStatusLabel_Serverstatus.Text = "aktiviert";
toolStripStatusLabel_Serverstatus.ForeColor = Color.Green;
}
private void AcceptTCP()
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
Task Work = new Task(() => DoWork());
Work.Start();
}
private void textBox_Output_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Send_Click(sender, e);
e.Handled = true;
textBox_Output.Focus();
}
}
}
Client:
public frmClient()
{
InitializeComponent();
Configuration Programmkonfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
HostnameServer = Programmkonfiguration.AppSettings.Settings["HostnameServer"].Value;
Port = Programmkonfiguration.AppSettings.Settings["Port"].Value;
textBox_Hostname.Text = GetLocalIPAddress();
textBox_Port.Text = Port;
toolStripStatusLabel_Status.Text = " nicht verbunden";
toolStripStatusLabel_Status.ForeColor = Color.Red;
textBox_Output.Focus();
}
private string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(HostnameServer);
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void button_Senden_Click(object sender, EventArgs e)
{
if (!(string.IsNullOrWhiteSpace(textBox_Output.Text)))
{
String s = "Client: " + textBox_Output.Text + Environment.NewLine;
textBox_Input.Text += s;
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
textBox_Output.Clear();
}
}
public void DoWork()
{
byte[] bytes = new byte[1024];
while (true)
{
if (ns.DataAvailable)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
this.SetText(Encoding.ASCII.GetString(bytes, 0, bytesRead));
}
}
}
private void SetText(string text)
{
if (this.textBox_Input.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox_Input.Text = this.textBox_Input.Text + text;
}
}
private void button_Connect_Click(object sender, EventArgs e)
{
string hostName = textBox_Hostname.Text;
int portNum = Convert.ToInt32(textBox_Port.Text);
client = new TcpClient(hostName, portNum);
ns = client.GetStream();
Work = new Task(() => DoWork());
Work.Start();
textBox_Input.Text += "Verbindung hergestellt." + Environment.NewLine;
button_Connect.Enabled = false;
toolStripStatusLabel_Status.Text = "verbunden";
toolStripStatusLabel_Status.ForeColor = Color.Green;
}
private void textBox_Output_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Senden_Click(sender, e);
e.Handled = true;
textBox_Output.Focus();
}
}
}
Each call to Accept on a listener socket accepts a single connection. At the moment, your server accepts a single connection request and then ignores the listener socket from that point onwards.
Normally, you'd want some form of "Accept loop" that continually calls Accept, sets up the server side resources for that connection and then loops back to call Accept again.
E.g. the trivial change is to do this:
private void AcceptTCP()
{
while(true)
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
Task Work = new Task(() => DoWork());
Work.Start();
}
}
But now you really have to think about what happens to ns - what happens if/when you want a second client connected simultaneously? Having NetworkStream be a single shared instance variable within the server isn't going to scale well.
Normally, you'd want to create some form of simple class that represents each connection + your server specific information relating to that connection. E.g. it would contain the NetworkStream, the current "state" of this connection (if you have modes or states), possibly the buffers that were last passed to a Read call as/when you start going async with this work, etc.

Cannot access a disposed Object C#

I am having a hard time. I am new to this. Can someone help me with this. Every time I call the _clientSocket.Close(); I got an error message.
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
There's no error in my code. It can run smooth but every time I open and close a form it comes up. I want to get rid of it. The program can run with it but its to irritating. Because when I try to open a client it will pop up. And when the time of the client is done, the form will close and the login will come out with another pop up of
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
I use _clientSocket.Close() because if I'm not closing the sockets it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
I'm doing this for my project and I'm just studying myself so some of the comments I really don't understand but I'm trying my best to learn from it thank you!
Your suggestions will much appreciated. Correct me if I'm wrong thank you!
This code is the Loginform when Server sends -O it will _clientSocket.Close(); and open the Form2. If Form2 use all the time it will back to Loginform and form2 _clientSocket.Close(); I call the _clientSocket.Close(); because the Server Checklistbox that catches all the connected sockets will be doubled if I don't close the Sockets.
Edited
Server
namespace RealVersion2
{
public partial class Server : Form
{
public class SocketT2h
{
public Socket _Socket { get; set; }
public string _Name { get; set; }
public SocketT2h(Socket socket)
{
this._Socket = socket;
}
}
private byte[] _buffer = new byte[1024];
public List<SocketT2h> __ClientSockets { get; set; }
List<string> _names = new List<string>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Server()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
__ClientSockets = new List<SocketT2h>();
this.list_Client.SelectionMode = System.Windows.Forms.SelectionMode.None;
}
private void Send_Click(object sender, EventArgs e)
{
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " );
}
else
{
Sendata(__ClientSockets[j]._Socket, "Server: " + txt_Text.Text);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
txt_Text.Text = "";
}
}
void Sendata(Socket socket, string noidung)
{
byte[] data = Encoding.ASCII.GetBytes(noidung);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
private void SetupServer()
{
try
{
lb_stt.Text = "Setting up server . . .";
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8000));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppceptCallback(IAsyncResult ar)
{
Socket socket = _serverSocket.EndAccept(ar);
__ClientSockets.Add(new SocketT2h(socket));
list_Client.Items.Add(socket.RemoteEndPoint.ToString());
lb_soluong.Text = "Number of clients connected: " + __ClientSockets.Count.ToString();
lb_stt.Text = "Client connected. . .";
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
if (socket.Connected)
{
int received;
try
{
received = socket.EndReceive(ar);
}
catch (Exception)
{
// client close connection
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
//taga tapoon ng panget
list_Client.Items.RemoveAt(i);
__ClientSockets.RemoveAt(i);
lb_soluong.Text = "Number of clients connected: "+__ClientSockets.Count.ToString();
}
}
//delete in list
return;
}
if (received!=0)
{
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
//lb_stt.Text = "Text received: " + text;
string reponse = string.Empty;
//reponse = "Server: Hi! You're Connected to the Librarian.";
if (text.Contains("##"))
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
list_Client.Items.RemoveAt(i);
list_Client.Items.Insert(i, text.Substring(1, text.Length - 1));
__ClientSockets[i]._Name = text;
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
return;
}
}
}
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
rich_Text.AppendText("\n" + __ClientSockets[i]._Name + ": " + text);
}
}
}
else
{
for (int i = 0; i < __ClientSockets.Count; )
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
__ClientSockets.RemoveAt(i);
lb_soluong.Text ="The number of clients connected: " + __ClientSockets.Count.ToString();
}
}
}
}
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void Server_Load(object sender, EventArgs e)
{
SetupServer();
}
private void Restartbtn_Click(object sender, EventArgs e)
{
string Restart = string.Empty;
Restart = "-r";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Restart);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Shutdownbtn_Click(object sender, EventArgs e)
{
string Shutdown = string.Empty;
Shutdown = "-s";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Shutdown);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void list_Client_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (list_Client.GetItemRectangle(i).Contains(list_Client.PointToClient(MousePosition)))
{
switch (list_Client.GetItemCheckState(i))
{
case CheckState.Checked:
list_Client.SetItemCheckState(i, CheckState.Unchecked);
break;
case CheckState.Indeterminate:
case CheckState.Unchecked:
list_Client.SetItemCheckState(i, CheckState.Checked);
break;
}
}
}
}
private void openPCToolStripMenuItem_Click_1(object sender, EventArgs e)
{
string Open = string.Empty;
Open = "-O";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Open);
//use [i] if u dont want name in list
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Server_FormClosing(object sender, FormClosingEventArgs e)
{
string Ext = string.Empty;
Ext = "exit";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
Application.Exit();
_serverSocket.Close();
}
}
private void End_Click(object sender, EventArgs e)
{
string Ext = string.Empty;
Ext = "close";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
}
}
Client
public partial class UserLog : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TimeSpan countdownClock = TimeSpan.Zero;
public UserLog()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Username = "User";
string Pass = "123";
if (Username == textBox1.Text && Pass == textBox2.Text)
{
MessageBox.Show("Login Successfully");
Usertimer User = new Usertimer(textBox1.Text);
User.Show();
this.Hide();
_clientSocket.Dispose();
_clientSocket.Close();
}
else
{
MessageBox.Show("Please Enter valid Username or Password");
}
}
byte[] receivedBuf = new byte[1024];
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
Usertimer us = new Usertimer(textBox1.Text);
us.Show();
});
});
NT.Start();
}
if (text == "Server: exit")
{
_clientSocket.Close();
Application.Exit();
}
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (ObjectDisposedException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
textBox4.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox5.Text), 8000);
//_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 100);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void button2_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_Load(object sender, EventArgs e)
{
LoopConnect();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
Form2 of the client
public partial class Usertimer : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Usertimer(string pass)
{
InitializeComponent();
label3.Text = pass;
}
byte[] receivedBuf = new byte[1024];
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.btnConnect_Click(null, null);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
if (text == "Server: close")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
UserLog Log = new UserLog();
Log.Show();
this.Close();
_clientSocket.Close();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
richTextBox1.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 8000);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void btnConnect_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##" + txName.Text);
_clientSocket.Send(buffer);
}
private void btnSend_Click(object sender, EventArgs e)
{
if (_clientSocket.Connected)
{
byte[] buffer = Encoding.ASCII.GetBytes(txt_text.Text);
_clientSocket.Send(buffer);
AppendtoTextBox(txName.Text + ": " + txt_text.Text);
}
txt_text.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
UserLog log = new UserLog();
log.Show();
this.Close();
_clientSocket.Close();
}
}
}
Like I answered in your previous question, you should spend the time to read these two pages. They will help you get your answer much faster.
There's no error in my code.
If you're getting an error message, then there's an error in your code.
every time I open and close a form
What form? There is no form in your example.
it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
What server? What checklistbox? We don't know what you are referring to here.
Without a minimal, complete and verifiable example, we can't help you very well. That being said, it looks like you are closing your _clientSocket. Once you've closed a socket you must re-open it or create a new one before you can use it again. You cannot call BeginReceive after you've closed your socket.
I was able to reproduce your error by creating a complete, minimal and verifiable example. Here is the code:
public partial class Form1 : Form
{
Socket _clientSocket;
public Form1()
{
InitializeComponent();
}
const int buffSize = 1024;
byte[] receivedBuf = new byte[buffSize];
Socket listenerSock;
Socket handlerSock;
private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
listenerSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenerSock.Bind(localEndPoint);
listenerSock.Listen(10);
listenerSock.BeginAccept(ServerAcceptAsync, null);
_clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.Connect(localEndPoint);
_clientSocket.BeginReceive(receivedBuf, 0, buffSize, SocketFlags.None, ReceiveData, null);
}
private void ServerAcceptAsync(IAsyncResult ar)
{
handlerSock = listenerSock.EndAccept(ar);
}
private void ReceiveData(IAsyncResult ar)
{
//try
//{
Debug.WriteLine("received data");
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Debug.WriteLine(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
private void button1_Click(object sender, EventArgs e)
{
var message = Encoding.UTF8.GetBytes("Server: -O");
handlerSock.Send(message);
}
}
I commented the code that was not necessary to reproduce. As expected, the problem is that you call ReceiveAsync after you call _clientSock.Close(). You can't do that. If you close the socket, you should not execute anymore code. Here is an example of how to fix this:
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
else
{
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}

i can´t run my app because i have a loop in my form_load |windows form application c#|

I have a problem in my hands.
I have a program in which the client (form1) has to try to reconnect whenever it can not connect to the server.
The loop that I have to do the reconnection is inside the Fomr_load so that the reconnection is automatic.
But the problem is that the application does not open until form_load is complete.
Who knows where I'm goin tell me please
private void Form1_Load(object sender, EventArgs e)
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
try
{
Socket Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(IP_End);
if (Client.Connected)
{
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
else
{
reconnect();
}
}
catch (SocketException)
{
reconnect();
}
}
private void reconnect()
{
try
{
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
Client.Connect(IP_End);
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
catch (SocketException)
{
reconnect();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (Client.Connected)
{
try
{
receive = STR.ReadLine();
label1.Invoke(new MethodInvoker(delegate () { label1.Text = (receive + "\n\r"); }));
receive = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
Have a boolean variable that you set to true once you connect successfully and then check that as well before calling reconnect(), so your loop should run once, set connectedSuccessfully = true, then next time it runs it will see that it's true and skip over the call to reconnect(). You probably also want to add a timer to maybe try once again after 1 second, then try again in 5 seconds, then again in 10 etc etc.

"A socket operation failed because the destination host was down" when connecting pc to mobie device

My project is to connecting pc with mobile device using 32feet.net library.
Until Now, my solution is doing steps like:
Scanning for devices in area.
pairing with selected device .
request pairing with mobile device and when it's okay this error appear :
"A socket operation failed because the destination host was down" and I don't know why and how to overcome this problem. Any help with this problem will be appreciated.
And my solution is:
namespace Bluetooth
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
items = new List<string>();
InitializeComponent();
}
private void Connect_Click(object sender, EventArgs e)
{
if(ServerStarted )
{
updateUI("Server Already Started");
return;
}
if(rbClient.Checked)
{
//ConnectAsClient();
StartScan();
}
else
{
ConnectAsServer();
}
}
private void StartScan()
{
listBox.DataSource = null;
listBox.Items.Clear();
items.Clear();
Thread bluethoothscanthread = new Thread(new ThreadStart(scan));
bluethoothscanthread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan()
{
updateUI("Starting Scan ...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan Completed......");
updateUI(devices.Length.ToString() + "devices discovered");
foreach(BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
UpdateDeviceList();
}
private void ConnectAsServer()
{
Thread BluethoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
BluethoothServerThread.Start();
}
private void ConnectAsClient()
{
throw new NotImplementedException();
}
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
bool ServerStarted = false;
public void ServerConnectThread()
{
ServerStarted = true;
updateUI("Server Started , Waiting For Clients ");
BluetoothListener bluelistner = new BluetoothListener(mUUID);
bluelistner.Start();
BluetoothClient conn = bluelistner.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mstream = conn.GetStream();
while(true)
{
// handle server connection
try
{
byte[] Received = new byte[1024];
mstream.Read(Received, 0, Received.Length);
updateUI("Received : " + Encoding.ASCII.GetString(Received));
byte[] Sent = Encoding.ASCII.GetBytes("Hello World ");
mstream.Write(Sent, 0, Sent.Length);
}
catch(IOException exception)
{
updateUI("Client has disconnected !!! ");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate ()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0 ;
};
Invoke(del);
}
private void UpdateDeviceList()
{
Func<int> del = delegate ()
{
listBox.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceinfo;
private void listBox_DoubleClick(object sender, EventArgs e)
{
deviceinfo = devices.ElementAt(listBox.SelectedIndex);
updateUI(deviceinfo.DeviceName + "Was Selected , attempting connect");
if( pairDevice())
{
updateUI("Device Paired.....");
updateUI("Starting Connect Thread");
Thread bluethoothClientThread = new Thread(new ThreadStart(ClientconnectThread));
bluethoothClientThread.Start();
}
else
{
updateUI("Pair Failed");
}
}
private void ClientconnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("Attempting Connect");
client.BeginConnect(deviceinfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
BluetoothEndPoint bep = new BluetoothEndPoint(deviceinfo.DeviceAddress, BluetoothService.AvctpProtocol);
BluetoothClient cli = new BluetoothClient();
client.Connect(bep); // the exception throw in this line //
Stream stream = cli.GetStream();
stream.ReadTimeout = 10000;
//Stream peerStream = cli.GetStream();
// client.Connect(BluetoothAddress.Parse(items(0)), mUUID);
//client.EndConnect(result);
//while(true)
//{
// while (!ready) ;
// stream.Write(message, 0, message.Length);
//}
//streaming(result);
if(result.IsCompleted)
{
// client.EndConnect(result);
// Stream stream = client.GetStream();
// stream.ReadTimeout = 1000;
updateUI("Ya rabbbbb");
//while (!ready) ;
//stream.Write(message, 0, message.Length);
}
}
void streaming (IAsyncResult result)
{
BluetoothListener listn = new BluetoothListener(mUUID);
listn.Start();
BluetoothClient conn = listn.AcceptBluetoothClient();
Stream peerstream = conn.GetStream();
bool rightconn = peerstream.CanRead;
if(rightconn)
{
updateUI("Now you can streaming");
}
else
{
updateUI("Not Yet");
}
}
string mypin = "1234";
private bool pairDevice()
{
if(!deviceinfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceinfo.DeviceAddress, mypin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
} // End of namespace
I think I followed same example with you and of course I encountered same problem.
Rest of my codes are same with yours until "private void ClientconnectThread()" function and here is mine;
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attempting connect");
//client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
BluetoothAddress addressSeleccionado = deviceInfo.DeviceAddress;
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
BluetoothEndPoint ep = new BluetoothEndPoint(addressSeleccionado, mUUID);
client.Connect(ep);
updateUI("connected");
Stream stream = client.GetStream();
while (true)
{
byte[] received = new byte[1024];
stream.Read(received, 0, received.Length);
updateUI("received: ");
for (int i = 0; i < 15; i++)
{
updateUI(received[i].ToString());
}
if (ready)
{
ready = false;
stream.Write(message, 0, message.Length);
}
}
}
With this code I can connect the remote device and implement basic send/receive data communication. In order to my search over internet, "if this code does not fit for you", you might think that 32feet is not compatible with your bluetooth driver. (by the way my PC's OS is 64bit Win7 and I use the internal BT device of my PC )
Best regards.

H7 Heart Rate Sensor in C# for Windows Desktop

Specifically, I need to develop a Desktop app that pulls data from H7 Heart Rate Sensor in C# code.
I have searched everywhere and i cant find nothing to help me.
The closest i cam is with this video (https://www.youtube.com/watch?v=Jn05CU3mxzo&list=UUizfLH6Q2igGUyTWO1bH3YA) tutorial but still it didn't find my H7 Heart Rate Sensor.
namespace _123
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
InitializeComponent();
items = new List<string>();
}
private void bGo_Click(object sender, EventArgs e)//button
{
if (serverStarted)
{
updateUI("server aleredy started");
return;
}
if (rbClient.Checked) {
startScan();
}
else{
connectAsServer();
}
}
private void startScan() {
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan ()
{
updateUI("Starting scan...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan complet");
updateUI(devices.Length.ToString() + "devices discovered");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void connectAsServer()
{
Thread bluetoothServerTherad = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerTherad.Start();
}
private void connectAsClient()
{
}
Guid mUUID = new Guid("ECC037FD-72AE-AFC5-9213-CA785B3B5C63");
bool serverStarted = false;
private void ServerConnectThread()
{
//throw new NotImplementedException();
serverStarted = true;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exeption)
{
updateUI("Client has disconected!");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(deviceInfo.DeviceName + " was selected, attemting connect");
if (pairDevice())
{
updateUI("device paired..");
updateUI("starting conected thread");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start();
}
else
{
updateUI("pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attepting connnection");
client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
client.EndConnect(result);
Stream stream = client.GetStream();
stream.ReadTimeout = 1000;
while (true)
{
while (!ready) ;
stream.Write(message, 0, message.Length);
}
}
string myPin = "1234";
private bool pairDevice()
{
if (!deviceInfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
}
This question is old now but here is my answer. So if you have Polar H7 and you are trying to get the Heart rate then I would recommend follow this Bluetooth Low Energy sample and just run the code it should work fine.
After you run this sample click on start enumerating and it will give you list of all the Bluetooth device .
Then find Polar H7 and click on it.
Go to step 2 and hit Connect and choose characteristic and service and you are done.

Categories

Resources