C# Server-Client App(One Server-Multi Client) - c#

I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?
Here is the my code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Timers;
using ClientServer;
namespace ClientServer
{
public partial class Form1 : Form
{
private TcpClient Client;
private StreamReader STR;
public StreamWriter STW;
public string receive;
public string text_to_send;
//int zaman;
public Form1()
{
InitializeComponent();
- Client = new TcpClient();
Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
foreach (IPAddress adress in LocalIP)
{
if(adress.AddressFamily== AddressFamily.InterNetwork)
{
textBox3.Text = adress.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listener.Start();
Client = listener.AcceptTcpClient();
STR = new StreamReader(Client.GetStream());
STW = new StreamWriter(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data background
backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
{
while(Client.Connected)
{
try
{
receive = STR.ReadLine();
if(receive=="soru1")
{
label7.Text = "Merhaba bu bir denemedir :)";
//zaman = 45;
timer1.Enabled = true;
}
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //veri gönder
{
if(Client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Gönderim başarısız!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connect Server
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
Client.Connect(IP_End);
if(Client.Connected)
{
textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data in background
backgroundWorker2.WorkerSupportsCancellation = true; //
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send Button
{
if(textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
//private void timer1_Tick(object sender, System.EventArgs e) //
//{
// zaman--; //timer her saniyede sayıyı 1 azaltacak
// label9.Text = zaman.ToString();
// if (zaman == 0)
// {
// timer1.Enabled = false;
// }
//}
}
}

Here a good links:
http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/
https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}

Related

How to make sure a C# application will respond after waking up from sleep (windows 10)?

I have made a simple port listener which listens to a port, and if the sent request is satisfactory, it will put the computer to sleep.
The application works when started, however, when I put the computer to sleep, and then wake it up;
before unlocking Windows application will not respond.
Is there a way to make the application respond even before unlocking Windows?
(Python console application will listen even before unlocking, but I don't want a cmd window open in taskbar.)
Code is available below
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace remoteShutdownandOtherStuffServer
{
public partial class Form1 : Form
{
CancellationTokenSource ts = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
//SystemEvents.PowerModeChanged += OnPowerChange;
}
//I have tried adding OnPowerChange event, but to no avail.
//private void OnPowerChange(object s, PowerModeChangedEventArgs e)
//{
// switch (e.Mode)
// {
// case PowerModes.Resume:
// ts.Cancel();
// CancellationToken ct = ts.Token;
// Task.Factory.StartNew(() =>
// {
// remoteShutdownListener(ct);
// }, ct);
// break;
// case PowerModes.Suspend:
// break;
// }
//}
private void remoteShutdownListener(CancellationToken ct)
{
TcpListener server = null;
textBox1.Invoke((MethodInvoker)delegate {
textBox1.Text = "";
textBox2.Text = "";
});
try
{
Int32 port = 10000;
IPAddress localAddr = IPAddress.Parse("192.168.1.5");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[1024];
String data = null;
while (true)
{
if (ct.IsCancellationRequested)
break;
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
bool allowed = false;
textBox1.Invoke((MethodInvoker)delegate {
textBox1.Text += "Received: " + data.ToString();
textBox2.Text += client.Client.RemoteEndPoint.ToString() ;
});
if(data.Contains("go to sleep"))
{
allowed = true;
}
var ipStrArray = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString().Split('.');
if(allowed && ipStrArray[0] =="192" && ipStrArray[1] == "168" && ipStrArray[2] == "1")
{
MessageBox.Show("it works");
Application.SetSuspendState(PowerState.Hibernate, true, true);
}
}
client.Close();
}
}
catch (Exception exc1)
{
//Console.WriteLine("SocketException: {0}", exc1);
}
finally
{
server.Stop();
}
}
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.Icon = (System.Drawing.Icon)Properties.Resources.remoteIcon;
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
remoteShutdownListener(ct);
}, ct);
}
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
Close();
}
else if (e.Button == MouseButtons.Left)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
}
//private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
//{
// this.Show();
// this.WindowState = FormWindowState.Normal;
//}
}
}

C# display a variable in a Textbox

i am sending Sensor information with a NUCLEOF411RE to my PC. I receive this data on the COM98 with a BaudRate of 115200. Now i want to program a Windows Application that will split my string and put it on my textboxes. until now i display the data with a Button_click event. It puts values on the Textboxes that actually are the real values. But if i move my Sensor and klick the button again there should be a lot more different values, but there are the same values on the textboxes. In addition i want to refresh the textboxes automatically and not with a button click.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace BNO080
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailablePorts();
}
public string comport;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
comport = comboBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(comboBox1.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
textBox5.Text = serial.ReadLine();
/*String[] Stringsizes = A.Split(new char[] {' '});
textBox1.Text = Stringsizes[0];
textBox2.Text = Stringsizes[1];
textBox3.Text = Stringsizes[2];
textBox4.Text = Stringsizes[3];*/
// textBox5.Text = A;
//Array.Clear(Stringsizes, 0, 3);
}
catch (Exception) { }
}
}
}
can someone help me?
Can you give more information why you use the Button_Click Event to read the text? Maybe it is a possible way for you to subscribe for the DataReceived-Event of the COM-port?
It would look something like this:
serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string receivedString = serial.ReadExisting();
//Do something here...
}
I'd do a couple things. First subscribe to the DataReceived event on the serial port. This event handler will get called when there is data available on the serial port. Then in the event handler you can read from the serial port and add it to your textbox. You can't add it directly (see the AppendText function) because the event handler is called with a different thread, only the UI thread can update UI components (or you'll get a cross-thread exception).
...
public Form1()
{
InitializeComponent();
getAvailablePorts();
// Subscribe to the DataReceived event. Our function Serial_DataReceived
// will be called whenever there's data available on the serial port.
serial.DataReceived += Serial_DataReceived;
}
// Appends the given text to the given textbox in a way that is cross-thread
// safe. This can be called by any thread, not just the UI thread.
private void AppendText(TextBox textBox, string text)
{
// If Invoke is required, i.e. we're not running on the UI thread, then
// we need to invoke it so that this function gets run again but on the UI
// thread.
if (textBox.InvokeRequired)
{
textBox.BeginInvoke(new Action(() => AppendText(textBox, text)));
}
// We're on the UI thread, we can append the new text.
else
{
textBox.Text += text;
}
}
// Gets called whenever we receive data on the serial port.
private void Serial_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadExisting();
AppendText(textBox5, serialData);
}
Because i want to add an rotating 3D cube i decided to switch to WPF. I heard it is much easier to implement a 3D graphic there. So i copied my code to the new WPF project. But now i got already problems to visualize my values on the Textboxes. It doesnt work. It looks like the Evenhandler did not fire an event while receiving Data from the com port.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Drawing;
namespace cube
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
getAvailablePorts();
serial.DataReceived += Serial_DataReceived;
}
public bool button3clicked = false;
public bool button4clicked = false;
public bool button5clicked = false;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
List<string> Itemlist = new List<string>();
String[] ports = SerialPort.GetPortNames();
Itemlist.AddRange(ports);
comboBox1.ItemsSource = Itemlist;
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || textBox6.Text == "")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click_1(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
textBox1.Text = "test";
}
private void AppendText(string[] text)
{
try
{
textBox1.Text = text[0];
textBox2.Text = text[1];
textBox3.Text = text[2];
textBox4.Text = text[3];
}
catch (Exception) { }
}
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
}
private void Safe_Position2(TextBox tBr2, TextBox tBi2, TextBox tBj2, TextBox tBk2, string[] text)
{
if (button4clicked == true)
{
tBr2.Text = text[0];
tBi2.Text = text[1];
tBj2.Text = text[2];
tBk2.Text = text[3];
button4clicked = false;
}
}
private void Safe_Position3(TextBox tBr3, TextBox tBi3, TextBox tBj3, TextBox tBk3, string[] text)
{
if (button5clicked == true)
{
tBr3.Text = text[0];
tBi3.Text = text[1];
tBj3.Text = text[2];
tBk3.Text = text[3];
button5clicked = false;
}
}
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadLine();
String[] text = serialData.Split(new char[] { ' ' });
AppendText(text);
Safe_Position1(textBox5, textBox7, textBox8, textBox9, text);
Safe_Position2(textBox10, textBox11, textBox12, textBox13, text);
Safe_Position3(textBox14, textBox15, textBox16, textBox17, text);
}
private void button3_Click(object sender, EventArgs e)
{
button3clicked = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4clicked = true;
}
private void button5_Click(object sender, EventArgs e)
{
button5clicked = true;
}
}
}

C#: serial com not showing the whole data

Dear experts i am trying to access the serial port programmatically through C#.I have interface a gsm module serially for communication.problem i am facing is if data is small m getting it perfectly but when i am reading the all messages{AT+CMGL="ALL"} i am receiving only half data on contrary in third party application i am receiving the whole data.
so want to know where the problem is coming whether i have to inc the size of input buffer where the Readexisting() function storing data or have to increase the timeout?.Last i checked we can not vary the size of buffer. please help.
my code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SERIAL_PORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavailableports();
}
void getavailableports()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
MessageBox.Show("please select port");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
// textBox2.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
textBox1.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("no");
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button6.Enabled = false;
button7.Enabled = false;
textBox1.Enabled = false;
//textBox2.Enabled = false;
}
private void button6_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text + "");
textBox1.Text = "";
}
private void button7_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadExisting();
}
}
}

Add a username to Server/Client Chat in C#

I'm working on a Chat Application on Windows Form using C# Socket Programming.
Currently, my App send messages as "ME" and receives messages as "FRIEND".
What I want is to add a textbox which asks Client for username and server receives messages as that username. Following is my code:
namespace ServerClientChat
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public string receive2;
public String text_to_send;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //getting own IP
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = address.ToString();
}
}
// textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
private void button3_Click(object sender, EventArgs e) //Connect to server
{
client = new TcpClient();
//set client side endpoint consisting of client's ip address and port
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text),int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if(client.Connected)
{
textBox2.AppendText(">> Connected to Server"+ "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any,int.Parse(textBox4.Text)); //Listens for connections from TCP network clients.
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream()); //Implements a TextReader that reads characters from a byte stream in a particular encoding.
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true; //Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //to receive data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("Friend: " + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //to send data
{
if(client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("Me: " + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Send Failed");
}
backgroundWorker2.CancelAsync();
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if(textBox1.Text!="")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
DialogResult f = MessageBox.Show("Welcome to My Chat App! Do you want to start your own Server? ", "Welcome!", MessageBoxButtons.YesNoCancel);
if (f == DialogResult.Yes)
{
button3.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
}
if (f == DialogResult.No)
{
button2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(this, new EventArgs());
}
}
}
}
You can create something like your own protocol and send it to a server.
<username>YourName</username>
<msg>Hello World</msg>
But in real-life applications you should use database with user authorization process.

How can i make my client-server app a multiclient-server app? C#

I have a little problem with setting my client-server app for multiple clients usage. I can connect to server and use one client. I modified a little the code to connect via second client, but i don't really know how can i read and send datas to server from second client that are visible also in first client and server. Any ideas/help? Thanks in advance!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Server_WF
{
public partial class Form1 : Form
{
private TcpClient client;
static List<TcpListener> listeners = new List<TcpListener>();
public StreamReader SR;
public StreamWriter SW;
public string otrzymano;
public String msg;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); // Pobieranie własnego IP
foreach(IPAddress adres in localIP)
{
if (adres.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = adres.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) // START SERVER
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listeners.Add(listener);
listener.Start();
client = listener.AcceptTcpClient();
SR = new StreamReader(client.GetStream());
SW = new StreamWriter(client.GetStream());
SW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); // Rozpocznij odbieranie danych
backgroundWorker2.WorkerSupportsCancellation = true; // Zdolność do usunięcia wątku
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Odbieranie danych
{
while(client.Connected)
{
try
{
otrzymano = SR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ktoś: " + otrzymano + "\n"); }));
otrzymano = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // Przesyłanie danych
{
if(client.Connected)
{
SW.WriteLine(msg);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ja: " + msg + "\n"); }));
}
else
{
MessageBox.Show("Wysyłanie nie powiodło się.");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) // Połącz z serwerem
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if(client.Connected)
{
textBox2.AppendText("Połączono z serwerem..." + "\n");
SW = new StreamWriter(client.GetStream());
SR = new StreamReader(client.GetStream());
SW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); // Rozpocznij odbieranie danych
backgroundWorker2.WorkerSupportsCancellation = true; // Zdolność do usunięcia wątku
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text != "")
{
msg = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
}
}
Oh dear, there's a lot to do in your code. First of all: don't call CancelAsync from your background worker code. It is not necessary and probably causes problem. Also, a background worker should never ever display MessageBoxes!
Secondly, a background worker is not the right tool in this case!
Thirdly: You need to make your code completely asynchronous. So please look into the BeginAcceptTcpClient. Then, handle each connected client in its own thread (NOT background worker!).
It's probably best you google for examples on how to do this, as this would be far too much to write up here.

Categories