I have a connection with TCP / IP. I want a multiple connection. I'm using SimpleTcp. It is very simple and useful for single connection. Unfortunately, I don't know how to make multiple connections with SimpleTcp.
The code below is the one used for single connection.
public void EthernetConnect()
{
try
{
string IpAddress = Ip.Text;
int Port = Convert.ToInt32(PortName.Text);
SimpleTcpClient client = new SimpleTcpClient(IpAddress, Port, false, null, null);
if (!client.IsConnected)
{
client.Connect();
if (client != null)
{
if (client.IsConnected)
{
Console.WriteLine("Connected");
client.Events.DataReceived += EthernetDataReceived;
client.Events.Connected += EthernetConnected;
client.Events.Disconnected += EthernetDisconnected;
timer.Start();
}
else
{
Console.WriteLine("Not Connected");
}
}
}
else
{
client.Events.DataReceived -= EthernetDataReceived;
}
}
catch
{
}
}
EthernetDataReceived
private void EthernetDataReceived(object sender, DataReceivedFromServerEventArgs e)
{
try
{
var Data = e.Data;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
How can the EthernetDataReceived function in single connection be used in multiple connections? Creating a separate function for each link sounds ridiculous.
I can use different structures other than SimpleTcp. But I'm a beginner please help?
EthernetDataReceived
is just an event handler that can be used to handle the DataReceived
event from any SimpleTcpClient
object. You can think of it as a method that may be called by any object from any thread.
Isn't there a problem if data comes from all of them at the same time?
Then the method will be called once per event that gets raised. This isn't an issue as long as you don't read or modify any shared data in the event handler. If you do this, you need to make the method thread-safe which is a topic of its own.
Also, how do I know which server data is coming from?
You should be able to cast the sender
argument and check the properties of the SimpleTcpClient
:
private void EthernetDataReceived(object sender, DataReceivedFromServerEventArgs e)
{
SimpleTcpClient client = (SimpleTcpClient)sender;
//...
}
Or check the DataReceivedFromServerEventArgs
whatever that is.