No Communication between Delphi and C# Applications using TCP-Sockets - c#

The C#-Application is the TCP-Server and Delphi-Application represents the TCP-Client polling Server for information.
I'm using Microsoft Visual Studio Community 2017 and .NET-Framework 4.5.1 for the C#-Application and Delphi 7 (Embarcadero) for the Client-Application.
Both Applications run on the same PC, therefore I set IP-Address to "localhost" or "127.0.0.1".
The Port is 12345.
class Program
{
static void Main(string[] args)
{
int port = 0;
IPHostEntry host;
IPAddress localAddress;
try
{
port = 12345;
host = Dns.GetHostEntry("localhost");
localAddress = host.AddressList[0];
Console.WriteLine("Server waits for a client");
// init Listener
TcpListener listener = new TcpListener(localAddress, port);
// start Listener
listener.Start();
// Wait for a client..
TcpClient c = listener.AcceptTcpClient();
Console.WriteLine("Connection established.");
//..
// Close connection
c.Close();
// stop Listener
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
My Problem is, that I get error # 10061 "Connection refused" in the Client (Delphi) Application when the socket tries to connect to the server.
TForm1 = class(TForm)
TcpClient1: TTcpClient;
btnConnect: TButton;
// ..
procedure TForm1.btnConnectClick(Sender: TObject);
begin
// try to connect to TCP-Server
TcpClient1.RemoteHost := 'localhost';
TcpClient1.RemotePort := '12345';
if not TcpClient1.Connect() then // Error 10061
begin
ShowMessage('No connection to server');
end
else
begin
ShowMessage('Connected with server.');
end;
end;
In Delphi I tried the component TcpClient as well as the Indy component TIdTCPClient - the error appears on both.
For testing purpose I wrote a Client-Application in C# where the error didn't occur (same address and port).
class Program
{
static void Main(string[] args)
{
try
{
// init Client
TcpClient c = new TcpClient("localhost", 12345);
Console.WriteLine("Connected to localhost.");
// ..
// close connection
Console.WriteLine("Close connection.");
c.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.WriteLine("Press Enter to exit... ");
string cmd = Console.ReadLine();
}
}
My guess is, that there is something between C# and Delphi, but I have no idea what.
Did anyone has an idea why I cannot establish a connection with the Delphi-Application?
Update: It seems to work, when the C#-Server accepts Clients from any IP-Address.
// ..
// host = Dns.GetHostEntry("localhost");
// localAddress = host.AddressList[0];
Console.WriteLine("Server waits for a client");
// init Listener
TcpListener listener = new TcpListener(IPAddress.Any, port);
//..

In C# localAddress can be of Address Family IPv4, IPv6 or others, I wasn't able to connect with my Delphi-Application that works with IPv4.
My current solution:
I loop through the AddressList and make sure that I get an IP-Address of IPv4-Family.
host = Dns.GetHostEntry("localhost");
for (int i = 0; i <= host.AddressList.Length - 1; i++)
{
if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) // check if family is IPv4
{
localAddress = host.AddressList[i];
// init Listener
listener = new TcpListener(localAddress, port);
// start Listener
listener.Start();
// ..
}
}

Related

C# Sockets communication between two computers

i want to let 2 c# apps each one is on a separate computer and both connected to the same ADSL router to send messages to each other i know that we have to use Sockets and tried many solutions on the internet but they are all working at the same computer but not working on a separate computers.
i believe that the problem is in the ip addresses but i tried a lot with no good results
is there any simple code to help please
i tried this function on server side
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
Console.WriteLine(ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
and this function in the client side
public static void StartClient()
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
please make sure that your client is connected to the same IP on which server is started. because it seems in your code that your client connecting to host which you getting it from localhost identity. For your testing purpose please hardcode the Server's IP address in your Remoteendpoint. if still the issue same then I will share code to test on a different networks.

No connection could be made because the target machine active refused it?

My problem is weird and i was not able to find a resolution from referring to other threads regarding this. I am getting the error when i run the microsoft Synchronous Server Socket Example, Synchronous Client Socket Example, on two systems which are part of the domain but i do not get this error when i run the same code on two systems which are part of the network but they are not part of the domain! Anyone know what might be causing the issue?
The things i have done to try to resolve are I made sure the port was open, switched off the firewall and antivirus as suggested by others with similar problem.But it has not helped.
Server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener {
// Incoming data from the client.
public static string data = null;
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and
// listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true) {
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true) {
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
break;
}
}
// Show the data on the console.
Console.WriteLine( "Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args) {
StartListening();
return 0;
}
}
Client Code::
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient {
public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPAddress ipAddress = IPAddress.Parse("172.21.98.122");//Server IP
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static int Main(String[] args) {
StartClient();
return 0;
}
}

C++ Client works only with localhost C# Server

I am working with C++ application which is windows service and C# server .
With localhost testing everything works great, but with virtualbox system or the same network computers it doesnt work.
I disabled windows firewall and antivirus.
Here is my C# Server most important code:
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse("192.168.1.2");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8517);
tcpListener = new TcpListener(localEndPoint);
tcpListener.Start();
tcpListenerThread = new Thread(listenerSocket);
tcpListenerThread.Start();
}
static void listenerSocket()
{
while (true)
{
try
{
Socket client = tcpListener.AcceptSocket();
clientSockets.Add(client);
}
catch (Exception exc)
{
return;
}
}
}
And here is my C++ client most important code(according msdn examples for c++ socket clients):
connectToServer(){
serviceState = DISCONNECTED;
ConnectSocket = INVALID_SOCKET;
sendbuf = "Client Service is ready";
recvbuflen = DEFAULT_BUFLEN;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
SaveEvent(L"WSAStartup failed");
}
else{
SaveEvent(L"WSAStartup success");
}
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
SaveEvent(L"Error creating socket for connecting to server");
WSACleanup();
}
else{
SaveEvent(L"Creating socket for connecting to server success");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr( std::string(serverIP.begin(), serverIP.end()).c_str());
address.sin_port = htons( serverPort );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &address, sizeof(address) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
serviceState = DISCONNECTED;
SaveEvent(L"Unable to connect to server");
WSACleanup();
}
else{
serviceState = CONNECTED;
SaveEvent(L"Connected to server : " + serverIP );
u_long iMode = 1;
ioctlsocket(ConnectSocket, FIONBIO, &iMode);
}
}
With localhost it works and i have client and server on the same ip but with different ports.
With different ips i got situation when server doesnt 'hear' client.
My log looks like this:
2017-03-31 18:01:30 Settings readed: server IP = 192.168.1.2, server port = 8517-
2017-03-31 18:01:30 WSAStartup success -
2017-03-31 18:01:30 Creating socket for connecting to server success-
2017-03-31 18:01:31 Unable to connect to server-
I would really appreciate any kind oif help i stuck with this almost one week.
I can that add ping to server ip works on client pc

Tcp Server/Client Application to communicate with other PCs

i'm trying to make an application which allows the connection between 2 PCs(i planned on making it multi threaded later but lets keep it more simple at the beginning). This could be either used for chatting or sending data to the other pc and he does something to the data and sends it back.
This is my coding so far:
Server:
class Program
{
private static StreamWriter serverStreamWriter;
private static StreamReader serverStreamReader;
private static bool StartServer()
{
//setting up Listener
TcpListener tcpServerListener = new TcpListener(IPAddress.Any, 56765);
tcpServerListener.Start();
Console.WriteLine("Server Started!");
Console.WriteLine("Waiting for Connection...");
Socket serverSocket = tcpServerListener.AcceptSocket();
try
{
if (serverSocket.Connected)
{
Console.WriteLine("Client connected to Server!");
//open network stream on accepted socket
NetworkStream serverSockStream = new NetworkStream(serverSocket);
serverStreamWriter = new StreamWriter(serverSockStream);
serverStreamReader = new StreamReader(serverSockStream);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
return true;
}
static bool once = false;
static void Main(string[] args)
{
//Set Console Window Stuff
Console.Title = "Server";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
Console.BufferWidth = 120;
Console.Clear();
//Start Server
if (!StartServer())
Console.WriteLine("Error while Starting Server!");
//Waiting till Client sends Something
while (true)
{
string data = "Append Something to Me - ";
if (!once)//that check -.-
{
serverStreamWriter.WriteLine(data);
serverStreamWriter.Flush();
once = true;
}
Console.WriteLine("Client: " + serverStreamReader.ReadLine());
if (serverStreamReader.ReadLine() != data)
{
serverStreamWriter.WriteLine(data);
serverStreamWriter.Flush();
}
}
}
}
Client:
class Program
{
private static StreamReader clientStreamReader;
private static StreamWriter clientStreamWriter;
private static bool ConnectToServer()
{
try
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 56765);
Console.WriteLine("Connected to Server!");
NetworkStream clientSockStream = tcpClient.GetStream();
clientStreamReader = new StreamReader(clientSockStream);
clientStreamWriter = new StreamWriter(clientSockStream);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
return true;
}
private static void SendToServer(string message)
{
try
{
clientStreamWriter.WriteLine(message);
clientStreamWriter.Flush();
}
catch (Exception se)
{
Console.WriteLine(se.StackTrace);
}
}
static void Main(string[] args)
{
//Set Console Window Stuff
Console.Title = "Client";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.BufferWidth = 120;
Console.Clear();
if (!ConnectToServer())
Console.WriteLine("Error while Connecting to Server!");
SendToServer("Send Me Data...");
//Waiting till Server sends Something
while (true)
{
string response = clientStreamReader.ReadLine();
Console.WriteLine(response + "|| Appending Text...");
response += "Appended Text!";
Console.WriteLine("Sended " + response + " back to server!");
SendToServer(response);
}
}
}
Even though this isn't really good coding, it works for me, BUT the main problem with this is it only works on my local machine. How would i make it so if i run the server app on my pc and my friend runs the client app on his pc those two connect!? Help would be really great since i wasn't able to found a detailed tutorial or such and i only created this Account to ask for help here :)
TcpClient tcpClient = new TcpClient("localhost", 3333);
Instead of "localhost", use the remote machine's address here.
Edit:
You don't seem to understand how this connection process works, so I'll try to explain it a little better.
Your server is opening up a socket on port 3333, listening for any connections. This process does not need any external IP adress.
You clients are trying to connect to the server. They need to know what server they're connecting to, so you need to supply them with an IP address. An example would be something like
TcpClient tcpClient = new TcpClient("127.0.0.1", 3333);
//this is identical to using "localhost"
There's no way for you to get around at some point using a remote address in the connection protocol. You can't just tell the client "connect on port 3333" and expect it to know exactly where it needs to connect.
The comment explaining how to resolve a local IP address isn't useful in your case, because what you ended up doing was just telling the client to connect to itself, as you resolved the client's IP address and tried to connect to that.
However, you can have multiple clients connect to the same server. In this case you won't need multiple remote IP addresses, you just tell all the clients to connect to the same remote address and then handle that on the server. This is where the RemoteEndPoint comes into effect.
At the server level you can use the RemoteEndPoint to find the IP address of the clients connecting to it, and use this IP address to return information to those clients.
All in all, you WILL have to use some hardcoded address for your initial
TcpClient tcpClient = new TcpClient(address, 3333);
step. There's no way around this.

Client_Server two .cs in one project issue

I have to get started with Client Server Communication for my application. To get started, I want to connect to local host.
Here's the code:
Server
public class serv
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList=new TcpListener(ipAd,1025);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 1025...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Client
public class clnt
{
public static void Main()
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",1025); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
The Project has two Main() functions. So,to avoid conflict i set serv.cs as StartupObject but resulted in no-access to client's console window to send message.
1).How to use /run such programs on local host?
I actually needed a good starting point for using Sockets but most of the apps available on net are either quite obsolete or more advanced.I already had worked on Sockets using Linux but new to this environment.
2).Any good example other than this?
I have already googled up alot but SO is my last hope!.The projects on CodeProject are using UI and a simple Console app is needed for startup.
More than your code is not necessary.
Do you start both projects?
You have to start the server first, and then the client, so the client can connect to the waiting server.

Categories