C#应用程序是TCP服务器,Delphi应用程序代表TCP客户端轮询服务器以获取信息。使用TCP-Sockets的Delphi和C#应用程序之间没有通信
我为客户端应用程序的C#应用程序和Delphi 7(Embarcadero)使用Microsoft Visual Studio Community 2017和.NET-Framework 4.5.1。
这两个应用程序运行在同一台PC上,因此我将IP地址设置为“localhost”或“127.0.0.1”。 港是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);
}
}
}
我的问题是,我得到错误#10061“拒绝连接”,在客户端(德尔福)应用程序时,插座尝试连接到服务器。
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;
在Delphi我试图组件的TcpClient以及印地组件TIdTCPClient - 上都出现错误。
为了测试目的,我在C#中编写了一个客户端应用程序,其中没有发生错误(相同的地址和端口)。
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();
}
}
我的猜测是,C#和Delphi之间有一些东西,但我不知道是什么。
有没有人有一个想法,为什么我不能建立与Delphi应用程序的连接?
更新:它似乎工作,当C#服务器接受来自任何IP地址的客户端。
// ..
// host = Dns.GetHostEntry("localhost");
// localAddress = host.AddressList[0];
Console.WriteLine("Server waits for a client");
// init Listener
TcpListener listener = new TcpListener(IPAddress.Any, port);
//..
Can yuo可以发布C#服务器的代码吗? –
我在上面的问题中添加了C#服务器和C#客户端的代码。 – topet
我希望能看到更多的代码,看看服务器端是如何监听的(例如https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v中的MSDN文档示例) = vs.110)的.aspx)。 –