Reputation: 11
I'm trying to get a TCP server to connect with "multiple" TCP clients.
My project is basically 2 applications, which is designed like a 3 tier model. In the data tier for each applications i want a socket connection, so i can send data(string values) from one application to the other. As i have multiple methods in my logic tier that i want to send with my socket connection (same client basically), i have a problem with my TCP server - that it only accepts one TCP client (for some reason i don't know).
Do I need some kind of loop, so my server does'nt close the connection?
I'm pretty new to TCP programming, so I will be very happy to get some help to get going with my project.
This is my code for my TCP client:
public class Tx_Data
{
const int PORT = 9000;
private TcpClient clientSocket;
public Tx_Data()
{
Console.WriteLine("Client startet");
clientSocket = new TcpClient();
clientSocket.Connect("192.168.122.169", 9000);
Console.WriteLine("Forbindelse oprettet");
}
public void sendDataTCP(string puls, string QT, string QTc)
{
NetworkStream outToServer = clientSocket.GetStream();
string line = "Puls: " + puls + ", QT: " + QT + ", QTc: "+ QTc;
LIB.writeTextTCP(outToServer, line);
outToServer.Flush();
}
}
When i call the sendDataTCP method in one of my Logic Tier methods it looks like this:
public void sendData()
{
Tx_Data tD = new Tx_Data();
string puls = beregnPuls().ToString();
string QT = beregn_QT().ToString();
string QTc = beregn_QTC().ToString();
tD.sendDataTCP(puls,QT,QTc);
}
My TCP server that recieve the data looks like this atm:
public class Rx_Alarm
{
const int PORT = 9000;
public Rx_Alarm()
{
TcpListener serverSocket = new TcpListener(IPAddress.Any, 9000);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(">> Accept connection from client");
NetworkStream io = clientSocket.GetStream();
Console.WriteLine(LIB.readTextTCP(io));
}
}
Upvotes: 0
Views: 1153
Reputation: 2716
I don't know about TCPListeners, but in good old fashion socket programming. You can create server code and tell it how many clients to listen to
enter code here
var socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
var ipLocal = new IPEndPoint ( IPAddress.Any ,##Port Number##);
//bind to local IP Address...
socListener.Bind( ipLocal );
//start listening...
socListener.Listen (4); // where 4 is the number of clients to listen simultaneously
// create the call back for any client connections...
socListener.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
Upvotes: 1